/**
 * jquery extend functions for tds
 * 1.dictree 树形字典
 * 2.outree 人员选择树
 * 3.newtree 自定义树
 * 4.showTip 提示框
 * 5.checkall 列表选择框：全清、全选
 * 6.validateform  可校验表单
 * 7.ajaxpager 分页
 */
(function($){
	
	$.fn.serializeJson=function(){
		var serializeObj={};
		var array=this.serializeArray();
		var str=this.serialize();
		$(array).each(function(){
			if(serializeObj[this.name]){
				if($.isArray(serializeObj[this.name])){
					serializeObj[this.name].push(this.value);
				}else{
					serializeObj[this.name]=[serializeObj[this.name],this.value];
				}
			}else{
				serializeObj[this.name]=this.value;	
			}
		});
		return serializeObj;
	};
	
	$.fn.readonly = function(options){
		var opts = $.extend({}, $.fn.readonly.defaults, options);
		return this.each(function() {
        	var $field = $(this);
        	var enable = opts.enable;
        	var isSubmit = opts.isSubmit;
        	if($field.attr('type') == 'hidden'){
        		$field.removeAttr('disabled');
        		return;
        	}
        	//保留原来的属性
        	if(!$field.attr('_disabled')){
	    		if($field.attr('disabled') == 'true' || $field.attr('disabled') == 'disabled'){
	    			$field.attr('_disabled', $field.attr('disabled'));
	    		}else{
	    			$field.attr('_disabled', 'false');
	    		}
	    		if($field.attr('readonly') == 'true' || $field.attr('readonly') == 'readonly'){
	    			$field.attr('_readonly', $field.attr('readonly'));
	    		}
        	}
        	if (enable) {
        		if ($field.is(':text') || $field.is('textarea')){
        			$field.addClass(opts.defaultClass);
        			if($field.hasClass('Wdate')){//mydate97 datepicker
        				$field.attr('disabled', 'true');
        			}
        		} else {
        			$field.addClass(opts.defaultClass);
        			$field.attr('disabled', 'true');
        		}
        		$field.attr('readonly', 'true');
        		$field.data('readonly', true);
        		if($field.data().validatebox && $field.data().validatebox.options.required){//如果字段在页面上写了必填，则去掉必填的属性
        			$field.data().validatebox.options.required = false;
        		}
        	} else {
        		$field.removeData('readonly');
        		$field.removeClass(opts.defaultClass);
        		$field.removeAttr('disabled').removeAttr('readonly');
        		if(isSubmit == false){//如果不是表单提交
	        		//如果本来就是只读的则恢复
	        		if($field.attr('_disabled') == 'true' || $field.attr('_disabled') == 'disabled'){
	        			$field.attr('disabled', 'true');
	        		}
	        		if($field.attr('_readonly') == 'true' || $field.attr('_readonly') == 'readonly'){
	        			$field.attr('readonly', 'true');
	        		}
        		}
        	}
        });
	};
	
    $.fn.readonly.defaults = {
    	enable: true,// 启用只读状态
    	isSubmit: false,// 是否是提交
        defaultClass: 'xm_zh_formdisablec'// 默认的样式名称
    };
	/**
	 * 分页控件
	 */
	$.fn.ajaxpager = function(options) {

        var opts = $.extend({}, $.fn.ajaxpager.defaults, options);

        return this.each(function() {
        	var $form = $(this);
        	var target = opts.target;
        	$form.unbind().ajaxForm({
    			target: target
    		});
        	// init data
        	$(':input[name=pageNumber]').val('1');
        	submitRequest();
    		
        	$(target).on('click', 'a.page', function(){
        		var page = $(this).attr('data');
        		var $pageNumber = $(':input[name=pageNumber]');
        		$pageNumber.val(page);
        		submitRequest();
        	});
        	$(target).on('click', 'a.topage', function(e){
        		var page = $.trim($(':input[name=inputPage]').val());
        		if((/^\d+$/.test(page))){
        			var $pageNumber = $(':input[name=pageNumber]');
            		$pageNumber.val(page);
        			submitRequest();
        		}
        	});
        	$(target).on('keypress', 'input[name=inputPage', function(e){
        		if(e.keyCode == 13){
	        		var page = $.trim($(this).val());
	        		if((/^\d+$/.test(page))){
	        			var $pageNumber = $(':input[name=pageNumber]');
	            		$pageNumber.val(page);
	        			submitRequest();
	        		}
	        		return false;
        		}
        	});
        	$(target).on('change', 'select[name=pageSize]', function(e){
        		$(target + ' input[name=pageNumber]').val('1');
    			submitRequest();
        	});
        	
        	$("#queryAd").bind('click', function(){
        		$("input[name='keyword']").val("");
        		var ajax_option={
        			dataType:"html",
					success:function(html){
						$(target).html('').html(html);
					}
				};
				$($form.parent().find('form')[0]).ajaxSubmit(ajax_option);
//        		$form.parent().find('form').submit();
        	});
        	$("#cleanAd").bind('click', function(){
        		$("input[name='keyword']").val("");
        		$("input[type='hidden']").not("input[name='dataurl']").not("input[name='metaurl']").not("input[name='defCode']").not("input[name='callback']").not("input[name='button']").not("input[name='showInfo']").not("input[name='isTotal']").not("input[name='initButton']").not("input[name='selectedDepartId']").not("input[name='selectedItem']").not("input[name='selectedDepartName']").val("");
        		$form.parent().find('form')[0].reset();
				if($('#contForms').val()!=""){
					$('#contForms').find('option').each(function(){
						if($(this).val()==""){
							$(this).attr("selected","selected");
						}
					});
				}
				if($('#paymentType').val()!=""){
					$('#paymentType').find('option').each(function(){
						if($(this).val()==""){
							$(this).attr("selected","selected");
						}
					});
				}
        	});
        	
        	/**
        	 * 分页回调方法，默认提交表单
        	 */
        	function submitRequest() {
        		var _callback = opts.callback || function() {
        			$form.submit();
        		};
        		_callback.call();
        	}
        });
    };

    $.fn.ajaxpager.defaults = {
        target: '#list'
    };
    

    $.fn.autosave = function(options){
    	var opts = $.extend({}, $.fn.autosave.defaults, options);
		return this.each(function() {    
			var $this = $(this);
			try{
				opts.timeInterval = parseInt(opts.timeInterval);
			}catch(e){
				opts.timeInterval = 0;
			}
			if(opts.timeInterval <= 0){
				return;
			}
			if(opts.reset == true){
				var intervalId = $this.data('intervalId');
				clearInterval(intervalId);
			}
			start($this, options);
		});
		function start($this, options){
			var interval = opts.timeInterval * 60000;
			var intervalId = setInterval(function() {
				$('#_action').val(-2);
				$this.submit();
			}, interval);
			$this.data('intervalId', intervalId);
		}
    };
    $.fn.autosave.defaults = {
    	isTask:false,
    	isDraft:false,
    	autoSaveInterval:''     //间隔时间，分钟
    };
	$.fn.validateform = function(options){
		var opts = $.extend({}, $.fn.validateform.defaults, options);
		return this.each(function() {    
			var $this = $(this);
			if(opts.isTask && opts.isDraft && opts.autoSaveInterval != ''){//是自己可编辑的，启动定时保存
				$this.autosave({timeInterval: opts.autoSaveInterval});
			}
			$this.data('init', true);
			initFields($this, opts);
			$this.removeData('init');
			//表单验证
			$this.unbind().bind('submit', function() {
				//防止重复提交
				if(!isSubmiting($(this))) {
					setSubmitStatus($(this));
			    	$(this).ajaxSubmit({
			    		dataType: 'json',
			    		beforeSerialize: function (form, options){
			    			if(isChangeWorker($this)){
			    				if(isSelectedWorker($this)){
			    					$(form).find(':input').readonly({enable: false, isSubmit: true});
					    			$(form).find(':radio').readonly({enable: false, isSubmit: true});
			    					return true;
			    				}else{
			    					selectChangeWorker($this);
			    					cleanSubmitStatus($this);
			    					return false;
			    				}
			    			}
			    			if(isAutoSave($this)){
			    				$(form).find(':input').readonly({enable: false, isSubmit: true});
				    			$(form).find(':radio').readonly({enable: false, isSubmit: true});
				    			return true;
			    			}
			    			if (opts.beforeSerialize){
			    				if(opts.beforeSerialize(form) === false){
			    					cleanSubmitStatus($this);
			    					return false;
			    				}
			    			}
			    			if(!(isSubmitBack($this) || isRollbackDraft($this))){//回退和退回拟稿人不校验表单必填
			    				validateDynamicFields($this, opts);
			    				var fields = $(form).find(':input.validatebox-invalid');
			    				for ( var i = 0; i < fields.length; i++) {
			    					var field = $(fields[i]);
			    					if (field.is(":visible") && !field.validatebox('isValid')) {
			    						cleanSubmitStatus($this);
			    						field.focus();
			    						$(document).scrollTop(field.position().top - 150);
			    						return false;
			    					}
			    				}
			    			}
			    			if(!isSave($this) && $('#comment').length > 0 && $.trim($('#comment').val()).length == 0){
			    				common.showTip({title: localeMsg.common.prompt, text: localeMsg.common.opinion, autoclose: false});
			    				cleanSubmitStatus($this);
			    				return false;
			    			}
			    			$(form).find(':input').readonly({enable: false, isSubmit: true});
			    			$(form).find(':radio').readonly({enable: false, isSubmit: true});
			    			return true;
			    		},
			    		beforeSubmit: function(data,form){
			    			if(isAutoSave($this)){
			    				$this.autosave({reset:true,timeInterval: opts.autoSaveInterval});
				    			return true;
			    			}
			    			if(opts.isTask && opts.isDraft && opts.autoSaveInterval != ''){
			    				$this.autosave({reset:true,timeInterval: opts.autoSaveInterval});
			    			}
			    			if($('#_action').val() == '1'){ 
								if($('#route').val() == ''){
									cleanSubmitStatus($this);
									$(':radio[name=s_opt1]').focus();
									common.showTip({title: localeMsg.common.prompt, text: localeMsg.common.chooseRouting});
									initFields($this, opts);
									return false;
								}
							}
			    			if(!(isSubmitBack($this) || isRollbackDraft($this) || isSelectedWorker($this))){//回退、改派和退回拟稿人不校验表单必填
								if(opts.beforeSubmit && opts.beforeSubmit(form, opts) === false){
									cleanSubmitStatus($this);
									initFields($this, opts);
									if(opts.beforeSubmitCallback){
										opts.beforeSubmitCallback(form, opts);
									}
				    				return false;
				    			}
			    			}
							maskWindow();
							return true;
			    		},
			    		success: function (data, statusText, $form) {
			    			if(statusText == 'success'){
			    				if(data.status==0){
			    					if(!isSave($this)){//如果提交成功隐藏顶部按钮，防止重复提交
			    						$('.top_button').hide();
			    					}
			    					if(opts.defaultCallback){
				    					opts.defaultCallback.call(this, data, opts.callback, $form, opts);
			    					}else{
				    					//opts.callback.call(this, data, $form);
				    					opts.onSuccess.call(this, data, $form);
				    				}
			    				}else {
			    					if(data && data.data && data.data.id){//如果服务端保存了业务数据，需要回写到表单中，调用onSuccess回调
			    						var id = $(':input[name=id]');
			    						id.val(data.data.id);
			    						opts.callback.call(this, data);
			    					}
			    					if(data.updateFlowMsg){//流程提交更新了流程状态时的错误提示
			    					common.showError({text:data.updateFlowMsg,autoclose:false, errorMsg:data.updateFlowException});
			    				}else if(data.errors && data.errors.length >0){
			    					var isFirstField = false;
			    					for ( var i = 0; i < data.errors.length; i++) {// 服务端校验错误
			    						var error = data.errors[i];
			    						var msg = error.defaultMessage;
			    						var re = /\[(.*)\]$/;
			    						var arguments = null;
			    						if(re.test(error.code)){// 错误是否有参数，例如maxLength[50]
			    							var rp = /\[(.*)\]/;
			    							var argumentStr = re.exec(error.code)[1];
			    							arguments = argumentStr.split(',');
			    							for ( var j = 0; j < error.codes.length; j++) {// 去掉参数和方括号
			    								error.codes[j] = error.codes[j].replace(rp, '');
											}
			    						}
			    						// 根据错误码依次在校验js文件中匹配本地化消息
			    						// 错误码是长度为4的数组，根据服务端的字段名和错误码生成，
			    						// 类似于[required.contractMain.name,required.name,required.java.lang.String,required]
			    						for ( var k = 0; k < error.codes.length; k++) {
			    							if(localeValidateMsg[error.codes[k]]){
				    							msg = localeValidateMsg[error.codes[k]];
				    							break;
				    						}
										}
			    						if(arguments && arguments.length > 0 && msg != null){// 错误参数替换消息文字格式化，用{0}表示第一个参数
			    							for ( var ii = 0; ii < arguments.length; ii++) {
			    								var re = new RegExp('\\{' + ii + '\\}', 'gm');
												msg = msg.replace(re, arguments[ii]);
											}
			    						} 
			    						var field = null;
			    						//服务端校验返回有2种，
			    						if(error.field){
			    							field = $(':input[name=' + error.field + ']');
			    						}else if(error.arguments && error.arguments.length == 1){
			    							field = $(':input[name=' + error.arguments[0] + ']');
			    						}
			    						if(field && field.length > 0){
			    							field.val($.trim(field.val())).focus();
			    							if(field.is(":hidden")){
			    								if(field.siblings('.validatebox-text').length == 1){// 日期控件
			    									field = field.siblings('.validatebox-text');
			    								}else if(field.siblings('#' + error.field + 'Path').length == 1){// 字典控件
			    									field = field.siblings('#' + error.field + 'Path');
			    								}else if(field.attr('pathId') && $('#' + field.attr('pathId')).length == 1){// 字典控件
			    									field = $('#' + field.attr('pathId'));
			    								}
			    							}
			    							if(error.code == 'required'){
			    								if($.trim(field.val()).length > 0){//如果有值则是配置错误或者赋值错误，弹框提示
			    									field.focus();
				    								$(document).scrollTop(field.position().top - 150);
			    									common.showTip({title: localeMsg.common.prompt, text: error.defaultMessage + '必填', autoclose: false});
			    								}
			    								field.validatebox({
			    									required: true,
			    									missingMessage: msg
			    								});
			    							} else {//在原有的校验上增加校验规则
			    								try{
			    									var opt = {invalidMessage:msg};
			    									opt.validType = [];
			    									opt.validType.push(error.code);
			    									if(field.data() && field.data().validatebox){
			    										if(field.data().validatebox.options.required){//如果原来就是必填的，现在还要必填
			    											opt.required = true;
			    										}
			    										var oldValidType = field.data().validatebox.options.validType;//增加服务器返回的校验规则
			    										if(oldValidType && oldValidType != ''){
			    											opt.validType.push(oldValidType);
			    										}
			    									}
			    									field.validatebox(opt);
			    								}catch(e){
			    								}
			    							}
			    							if(isFirstField == false){
			    								isFirstField = true;
			    								if(field.is(":visible")){
			    									field.focus();
			    									$(document).scrollTop(field.position().top - 150);
			    								}else{
			    									common.showTip({title: localeMsg.common.prompt, text: error.defaultMessage + '校验错误', autoclose: false});
			    								}
			    							}
			    						}else{//字段不存在，弹框提示
			    							common.showTip({text:msg,autoclose:false});
			    						}
									}
			    					if(opts.onError){
			    						opts.onError.call(this, data, $form);
			    					}
			    				} else if(data.flowtip && data.flowtip.length >0){//显示流程校验提示
			    					var msg = new Stringbuilder();
			    					for(var i=0;i<data.flowtip.length;i++){
			    						var tip = data.flowtip[i];
			    						var code = tip.code;
			    						if('actors.required' == code && $("input[name='toworkNum']").val() > 1){//如果提示指定处理人且表单的待办数量大于1则需要修改为1并情况路由才能选人
			    							$("input[name='toworkNum']").val(1);
			    							$("#workflowDiv").find("input#route").val('');
			    						}
			    						var m = localeValidateMsg[tip.code];
			    						if(m == undefined){
			    							m = tip.message;
			    						}
			    						msg.append(m);
			    						msg.append("<br/>");
			    					}
			    					msg = msg.toString();
			    					if($.trim(msg).length>0){//显示错误提示
			    						common.showTip({text:msg,autoclose:false,callback:function(){
			    							opts.callback.call(this, data);
			    						}});
			    						data.flowtip = [];
			    					}else{
			    						opts.callback.call(this, data);
			    					}
			    				}
			    				}
			    			}
			    			initFields($this, opts);
			    		},
			    		error: function(xhr, textStatus, errorThrown){
			    			defaultAjaxError(xhr, textStatus, errorThrown);
			    		},
			    		complete: function(xhr, statusText){
			    			cleanSubmitStatus($this);
			    			if(opts.isTask && opts.isDraft && opts.autoSaveInterval != ''){
			    				$this.autosave({reset:true,timeInterval: opts.autoSaveInterval});
			    			}
			    		}
					});
				}
				return false;
			});
			$('.wf_button').show();//把刚开始隐藏的流程按钮显示
		});
		function getClientOffset(){
			if(document.compatMode=="BackCompat"){
			return {width:Math.max(document.body.scrollWidth,document.body.clientWidth),height:Math.max(document.body.scrollHeight,document.body.clientHeight)};
			}else{
			return {width:Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth),height:Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight)};
			}
		};
		/**
		 * 在当前窗口增加遮罩且提示文字位于窗口中间
		 * @param options
		 */
		function maskWindow(options){
		    var default_setting = {
		        selector: "body",
		        tip: "正在处理,请稍候..."
		    };
		   var opts = $.extend({}, default_setting, options);
		   $("<div class=\"datagrid-mask\"></div>").css({"z-index":"99",display:"block",width:"100%",height:getClientOffset().height}).appendTo(opts.selector); 
		   var top = $(document).scrollTop() + ($(window).height() / 2);
		   $("<div class=\"datagrid-mask-msg\"></div>").html(opts.tip).appendTo(opts.selector).css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:top}); 
		};
		function unmaskWindow(){
		  $(".datagrid-mask").remove();
		  $(".datagrid-mask-msg").remove();
		};
		function isAutoSave($this){
			return $('#_action').val() == '-2';
		};
		function isSave($this){
			return $('#_action').val() == '0';
		};
		//是否是退回
		function isSubmitBack($this){
			return $('#_action').val() == '-1';
		};
		//是否是改派（变更处理人）
		function isChangeWorker($this){
			return $('#_action').val() == '-98';
		};
		//是否是退回拟稿
		function isRollbackDraft($this){
			return $('#_action').val() == '-99';
		};
		function isSubmiting($this){
			return $this.data("submiting") == true;
		};
		function setSubmitStatus($this){
			$this.data("submiting", true);
		};
		function cleanSubmitStatus($this){
			$this.removeData("submiting");
			unmaskWindow();
			$this.find("input[name='_change2ActorId_']").remove();
		};
		//是否选择了更改处理人的人员
		function isSelectedWorker($this){
			return $("input[name='_change2ActorId_']").length == 1 && $("input[name='_change2ActorId_']").val() != '';
		};
		function selectChangeWorker($this){
			common.dialog({
				url : baseURL + "/workflow/changeTowork",
				title : "变更环节处理人",
				width:400,
				height : 330,
				param : param,
				resizable : true,
				confirm : function() {
					var	actorId = $("input[name='actorId']").val();
					if("" != actorId){
						if($this.find("input[name='_change2ActorId_']").length == 0){
							$('<input name="_change2ActorId_" type="hidden"/>').appendTo($this);
						}
						$("input[name='_change2ActorId_']").val(actorId);
						$this.submit();
					}else{
						common.showTip({text:"请指定处理人"});
					}
				}});
		};
		//校验动态添加的字段
		function validateDynamicFields($this, opts){
			if(opts.isTask && $this.data('dynamicFields')){
				var dynamicFields = $this.data('dynamicFields');
				for(var i = 0; i < dynamicFields.length; i++){
					var f = dynamicFields[i];
					var field = $this.find(':input[name=' + f.name + ']');
					if(field.length > 0){
						for ( var j = 0; j < field.length; j++) {
							var opt = {};
							$(field[j]).readonly({enable:false});
							if($(field[j]).data() && $(field[j]).data().validatebox){//如果原来已经有校验
								if(f.attr == 2 && !$(field[j]).data().validatebox.options.required){//如果原来不是必填的，要增加必填(存在原来是numberbox的情况)
									var opt = $(field[j]).data().validatebox.options;
									opt.required = true;
									$(field[j]).validatebox(opt);
								}
								continue;
							}
							if(f.attr == 2){
								opt = {
										required: true,
										missingMessage: f.lable?f.lable+'必填':'必填'
								};
							}
							if(f.validType && f.validType != ''){//服务端配置的校验类型
								opt.validType = f.validType;
							}
							$(field[j]).validatebox(opt);
						}
					}
				}
			}
		};
		function initFields($this, opts){
			if(opts.permission === true){
				$this.find(':input').readonly();
				$this.find(':radio').readonly();
				if($this.data('init')){//表单初始化时控制
					$this.find('.s_btnwork').hide().attr('_hide','1');
					$this.find("a[name='attach_delete_button']").hide();
				}			
			}
			
			$this.find(':input[name=comment]').readonly({enable:false});//常用意见
			$this.find(':radio[name=s_opt1]').readonly({enable:false});//路由选择
			$this.find(':checkbox[name=ractor]').readonly({enable:false});//最近选择人
			$this.find(':input[name=select2]').readonly({enable:false});//选择常用意见下拉框
			
			$this.find(':checkbox').readonly({enable:false});
			if(opts.isTask && opts.fields && opts.fields.length > 0){
				var dynamicFields = [];
				for(var i = 0; i < opts.fields.length; i++){
					var f = opts.fields[i];
					if(f.type == '1'){//按钮
						var btn = $this.find('.' + f.name);
						if(btn.length == 0){
							btn = $this.find('#' + f.name);
						}
						if(btn.length == 0){
							btn = $this.find("a[name='"+f.name+"']");
						}
						if(btn.length > 0){
							if(btn.is(':input')){
								btn.readonly({enable:false});
							}else{
								btn.show().removeAttr('_hide');
							}
						}
						continue;
					}
					var field = $this.find(':input[name=' + f.name + ']');
					if(field.length == 0){//未找到字段，可能是子表
						dynamicFields.push(f);
						continue;
					}
					if(field.is(":hidden")){
						if(field.length == 1){
							if(field.siblings('.validatebox-text').length == 1){// 日期控件
								field = field.siblings('.validatebox-text');
							}else if(field.siblings('#' + f.name + 'Path').length == 1){// 字典控件
								field = field.siblings('#' + f.name + 'Path');
							}else if(field.attr('pathId') && $('#' + field.attr('pathId')).length == 1){// 字典控件
								field = $('#' + field.attr('pathId'));
							}else if(field.siblings('.numberbox').length > 0){//numberbox
								field = field.siblings('.numberbox');
							}else{
								field.readonly({enable:false});
								continue;
							}
						}else{
							for ( var j = 0; j < field.length; j++) {
								var t = $(field[j]);
								if(t.siblings('.validatebox-text').length == 1){// 日期控件
									t = t.siblings('.validatebox-text');
								}else if(t.siblings('#' + f.name + 'Path').length == 1){// 字典控件
									t = t.siblings('#' + f.name + 'Path');
								}else if(t.attr('pathId') && $('#' + t.attr('pathId')).length == 1){// 字典控件
									t = $('#' + t.attr('pathId'));
								}else if(t.siblings('.numberbox').length > 0){//numberbox
									t = t.siblings('.numberbox');
								}else{
									t.readonly({enable:false});
									continue;
								}
								t.readonly({enable:false});
								if(f.attr == 1){//选填
									if(t.data() && t.data().validatebox){//如果原来已经有校验则跳过
										continue;
									}
									t.validatebox({
										validType: f.validType
									});
								}else if(f.attr == 2){// 必填
									if(t.is(":visible")){//不可见的必填字段不校验
										t.attr("required", true);
										if(t.data() && t.data().validatebox){//如果原来已经有校验
											if(!t.data().validatebox.options.required){//如果原来不是必填的，要增加必填(存在原来是numberbox的情况)
												var opt = t.data().validatebox.options;
												opt.required = true;
												t.validatebox(opt);
											}
											continue;
										}
										var opt = {
												required: true,
												missingMessage: f.lable?f.lable+'必填':'必填'
										};
										if(f.validType && f.validType != ''){//服务端配置的校验类型
											opt.validType = f.validType;
										}
										t.validatebox(opt);
									}
								}
							}
						}
					}
					field.readonly({enable:false});
					if(f.attr == 1){//选填
						if(field.data() && field.data().validatebox){//如果原来已经有校验则跳过
							continue;
						}
						field.validatebox({
							validType: f.validType
						});
					}else if(f.attr == 2){// 必填
						if(field.is(":visible")){//不可见的必填字段不校验
							field.attr("required", true);
							if(field.data() && field.data().validatebox){//如果原来已经有校验
								if(!field.data().validatebox.options.required){//如果原来不是必填的，要增加必填(存在原来是numberbox的情况)
									var opt = field.data().validatebox.options;
									opt.required = true;
									field.validatebox(opt);
								}
								continue;
							}
							var opt = {
									required: true,
									missingMessage: f.lable?f.lable+'必填':'必填'
							};
							if(f.validType && f.validType != ''){//服务端配置的校验类型
								opt.validType = f.validType;
							}
							field.validatebox(opt);
						}
					}
				}
				if(dynamicFields.length > 0){
					$this.data('dynamicFields', dynamicFields);
				}
				//后续要将隐藏的上传、删除、链接都要remove掉。此处方法待
			}
			if(opts.afterInit){
			    opts.afterInit();
			}
		};
	};
	/**
	 * 默认选项
	 */
	$.fn.validateform.defaults = {
		isTask: false,				// 是否是当前用户的待办任务
		autoSaveInterval:0,
		permission: true
	};
	$.fn.readonlyForm = function(options){
		var opts = $.extend({}, $.fn.readonlyForm.defaults, options);
		return this.each(function() {    
			var $this = $(this);
			readonlyFields($this, opts);
			$this.unbind().bind('submit', function() {
				return false;
			});
			if(opts.afterInit){
			    opts.afterInit();
			}
		});
		function readonlyFields($this, opts){
			$this.find(':input').unbind().readonly();
			$this.find(':radio').unbind().readonly();
			$this.find('a[class!=switchtab]').unbind();
			$this.find('.s_btnwork').hide();
			$this.find("a[name='attach_delete_button']").hide();
			$this.find('.s_btnwork').hide().attr('_hide','1');
			
			$this.find("a[name='attach_delete_button']").hide();
			$('.c_comp').off();
		}
	};
	/**
	 * 默认选项
	 */
	$.fn.readonlyForm.defaults = {
	};
	/**
	 * 树形字典插件(只使用于input元素)
	 * options = {
	 *  title: "请选择",				// 弹窗标题
		width: 320,					// 宽度
	    height: 480,				// 高度
	    modal: true,				// 是否为模式窗口
	    confirm: function() {},		// 确定按钮回调函数
	    url: "/dic/tree", 			// 请求地址
	    checkbox: false,			// 是否多选
		cascadeCheck: true,			// 是否级联选择
		onlyLeafCheck: false		// 是否仅叶子节点可选
		}
	 * 
	 */
	$.fn.dictree = function(options){
		var opts = $.extend({}, $.fn.dictree.defaults, options);
		
		return this.each(function() {    
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			$this.bind("click", function() {
				// 只读字段且不是必填字段不响应事件
				if($(this).data('readonly')){
					if(!($(this).data().validatebox && $(this).data().validatebox.options.required)){
						return;
					}
				}
				// 树形窗口元素
				var t = $.fn.dictree.getId($this);
				activeloadMask();
				if($('#treediv' + t).length == 1){
					if(o.cache==true){
						$('#treediv' + t).dialog('open');
						return;
					}else {
						destroy($('#treediv' + t));
					}
				}
				var ser = '';
				if(o.showSearch){
					ser = '<div class="modle_popinput" style="margin-top:0px;"><input value="搜索关键字" onfocus="if(this.value==\'搜索关键字\'){this.value=\'\';this.style.color=\'#2b2b2b\'}" class="modle_popinputin ac_input" name="keyword" onblur="if(this.value==\'\'){this.value=\'搜索关键字\';this.style.color=\'#aaa\'}" autocomplete="off">	</div>';
				}
				$("body").append('<div class="white_content xm_newchoosep" id="treediv' + t + '">' + ser + '<ul id="easytree' + t + '"></ul></div>');
				
				// 弹出窗口
				$('#treediv' + t).dialog({
					title: o.title,
					width: o.width,
					height: o.height,
					modal: o.modal,
					onClose: function(){
						destroyloadMask();
					},
					buttons: [{
						text: localeMsg.common.confirm,
						selected: true,
						handler: function(){
							onSelect(o, t);
						}
					}, {
						text: localeMsg.common.cancel,
						handler: function(){
							var selNode = $("#easytree" + t).tree("getSelected");
							// 取消事件回调方法
							o.cancel(selNode);
							destroyloadMask();
							$('#treediv' + t).dialog('close');
						}
					}]
				});
				
				var url = o.url;	// 请求地址
				var param = "";		// 请求参数
				if (o.param) {
					for (var key in o.param) {
						param += key + "=" + o.param[key] + "&";
					}
					if(o.pathLevel){
						param += "pathLevel=" + o.pathLevel;
					}
					param = param.lastIndexOf("&") == (param.length - 1)
							? param.substring(0, param.length - 1) : param;
					url += "?" + param;
				}
				
				if($("input[name='"+o.idName+"ext1']").length!=0){
					if($("input[name='"+o.idName+"ext1']").val().length!=0){
						url += "&extParam=ext1&extValue="+$("input[name='"+o.idName+"ext1']").val();
					}
				}
				
				if($("input[name='"+o.idName+"ext2']").length!=0){
					if($("input[name='"+o.idName+"ext2']").val().length!=0){
						url += "&extParam=ext2&extValue="+$("input[name='"+o.idName+"ext2']").val();
					}
				}
				
				if($("input[name='"+o.idName+"ext3']").length!=0){
					if($("input[name='"+o.idName+"ext3']").val().length!=0){
						url += "&extParam=ext3&extValue="+$("input[name='"+o.idName+"ext3']").val();
					}
				}
				
				if($("input[name='"+o.idName+"ext4']").length!=0){
					if($("input[name='"+o.idName+"ext4']").val().length!=0){
						url += "&extParam=ext4&extValue="+$("input[name='"+o.idName+"ext4']").val();
					}
				}
				
				if($("input[name='"+o.idName+"ext5']").length!=0){
					if($("input[name='"+o.idName+"ext5']").val().length!=0){
						url += "&extParam=ext5&extValue="+$("input[name='"+o.idName+"ext5']").val();
					}
				}
				
				// 初始化树
				$("#easytree" + t).tree({
					url: url,
					checkbox: o.checkbox,
					cascadeCheck: o.cascadeCheck,
					onlyLeafCheck: o.onlyLeafCheck,
					loadFilter: function(data) {
						return $.fn.dictree.dataFilter(data);
					},
					onLoadSuccess: function(node, data) {
						//设置纵向滚动条，IE8会不能出现滚动条
						$("#easytree" + t).parent().css({'overflow-y':'scroll'});
						//远程检索
						var searchUrl = url.replace('/dic/tree', '/dic/tree/search');
						var opt = {
								callback:function(data){
									var $tree = $("#easytree" + t);
									var node = $tree.tree('find', data.id);
									$tree.tree('select', node.target);
									$tree.tree('expandTo', node.target);
						}};
						autocompleteRemortDicTree($('#treediv' + t).find(":input[name=keyword]"), searchUrl, opt);
					},
					// 加载出错
					onLoadError: function(xhr, textStatus, errorThrown){
						defaultAjaxError(xhr, textStatus, errorThrown);
					},
					// 单击展开
					onClick: function(node){
						$(this).tree("expand", node.target);
					},
					// 双击选中
					onDblClick: function(node){
						var children = $(this).tree("getChildren", node.target);
						if (children && children.length > 0 && o.onlyLeafCheck) {
							return;
						}
						if(o.checkbox){
							$(this).tree("check", node.target);
						}
						onSelect(o, t);
					},
					onBeforeSelect: function(node) {
						var children = $(this).tree("getChildren", node.target);
						if (children && children.length > 0 && o.onlyLeafCheck) {
							return false;
						}
					},
					onSelect: function(node) {
						var attr = {
								locale: node.attributes.locale,
								name: node.attributes.name,
								nameEn: node.attributes.nameEn,
								code: node.attributes.ext1 || node.attributes.code,
								codes: node.attributes.ext1 || node.attributes.code,
								localeName: node.attributes.locale || node.attributes.localeName,
								localeNames: node.attributes.locale || node.attributes.localeName,
								zhnames: node.attributes.name || node.attributes.zhnames,
								ennames: node.attributes.nameEn || node.attributes.ennames,
								externalCode: node.attributes.externalCode,
								ext1:node.attributes.ext1,
								ext2:node.attributes.ext2,
								ext3:node.attributes.ext3,
								ext4:node.attributes.ext4,
								ext5:node.attributes.ext5
						};
						// 更新选中节点属性
						$(this).tree("update", {
							target: node.target,
							attributes: addPath(this, node.target, attr, o.pathSpliter)
						});
					},
					onCheck:function(node, checked){
						var attr = {
								code: node.attributes.ext1 || node.attributes.code,
								codes: node.attributes.ext1 || node.attributes.codes,
								localeName: node.attributes.locale || node.attributes.localeName,
								localeNames: node.attributes.locale || node.attributes.localeNames,
								zhnames: node.attributes.name || node.attributes.zhnames,
								ennames: node.attributes.nameEn || node.attributes.ennames,
								externalCode: node.attributes.externalCode
						};
						// 更新选中节点属性
						$("#easytree" + t).tree("update", {
							target: node.target,
							attributes: addCheckPath("#easytree" + t, node.target, attr, o.pathSpliter)
						});
					}
				});
			});
					
		});
		function onSelect(o, t){

			var selNode;
			if (o.checkbox) {
				selNode = $("#easytree" + t).tree("getChecked", 'checked');
				if(selNode.length > o.multiMax){
					common.showTip({text:'选择数量不能超过' + o.multiMax + '个'});
					return;
				}
				var pathValue = [];
				var idValue = [];
				var zhValue = [];
				var enValue = [];
				for (var i = 0;i < selNode.length; i++) {
					pathValue.push(selNode[i].attributes.localeNames);
					idValue.push(selNode[i].attributes.code);
					zhValue.push(selNode[i].attributes.zhnames);
					enValue.push(selNode[i].attributes.ennames);
				}
				if (o.pathName) {
					$('input[id="'+o.pathName + '"]').val(pathValue.join(";"));
					$('input[id="'+o.pathName + '"]').attr('title',pathValue.join(";"));
				}
				if (o.idName) $('input[id="'+o.idName + '"]').val(idValue.join(";"));
				if (o.zhName) $('input[id="'+o.zhName + '"]').val(zhValue.join(";"));
				if (o.enName) $('input[id="'+o.enName + '"]').val(enValue.join(";"));
			} else {
				selNode = $("#easytree" + t).tree("getSelected");
				if(selNode == null){
					selNode = {id:'',text:'',attributes:{code:'',localeNames:'',zhnames:'',ennames:''}};
				}
				if (o.pathName) {
					if (o.selectPath){
						if(o.selectRoot){
							$('input[id="'+o.pathName + '"]').val(selNode.attributes.localeNames);
						}else{
							var v = selNode.attributes.localeNames;
							if(v && v.indexOf(",") != -1){
								v = v.substring(v.indexOf(",")+1);
							}
							$('input[id="'+o.pathName + '"]').val(v);
						}
						if (o.zhName) $('input[id="'+o.zhName + '"]').val(selNode.attributes.zhnames);
						if (o.enName) $('input[id="'+o.enName + '"]').val(selNode.attributes.ennames);
					} else {
						$('input[id="'+o.pathName + '"]').val(selNode.text);
						if (o.zhName) $('input[id="'+o.zhName + '"]').val(selNode.text);//不选择全路径
						if (o.enName) $('input[id="'+o.enName + '"]').val(selNode.nameEn);
					}
					$('input[id="'+o.pathName + '"]').attr('title',selNode.attributes.localeNames);
				}
				if (o.idProperty) $('input[id="'+o.idProperty + '"]').val(selNode.id);
				if (o.idName) $('input[id="'+o.idName + '"]').val(selNode.attributes.code);
				if (o.codeName) $('input[id="'+o.codeName + '"]').val(selNode.attributes.code);
				
				if(o.ext1){
					if($("input[name='"+o.idName+"ext1']").length!=0){
						$("input[name='"+o.idName+"ext1']").val(selNode.attributes.ext1);
					}
				}
				
				if(o.ext2){
					if($("input[name='"+o.idName+"ext2']").length!=0){
						$("input[name='"+o.idName+"ext2']").val(selNode.attributes.ext2);
					}
				}
				
				if(o.ext3){
					if($("input[name='"+o.idName+"ext3']").length!=0){
						$("input[name='"+o.idName+"ext3']").val(selNode.attributes.ext3);
					}
				}
				
				if(o.ext4){
					if($("input[name='"+o.idName+"ext4']").length!=0){
						$("input[name='"+o.idName+"ext4']").val(selNode.attributes.ext4);
					}
				}
				
				if(o.ext5){
					if($("input[name='"+o.idName+"ext5']").length!=0){
						$("input[name='"+o.idName+"ext5']").val(selNode.attributes.ext5);
					}
				}
				
				if (o.useId && o.idName){
					$('input[id="'+o.idName + '"]').val(selNode.id);
				}
				if (o.topProperty){
					$(':input[name="'+o.topProperty + '"]').val(selNode.topName);
				}
				if (o.topCodeProperty){
					$(':input[name="'+o.topCodeProperty + '"]').val(selNode.topCode);
				}
				if (o.itemProperty){
					$(':input[name="'+o.itemProperty + '"]').val(selNode.text);
				}
				if (o.itemCodeProperty){
					$(':input[name="'+o.itemCodeProperty + '"]').val(selNode.code);
				}
			}
			
			// 确定事件回调方法
			if (o.confirm) {
				o.confirm.call($('#'+t), selNode);
			}
			$("input[name='" + o.pathName + "']").focus();
			destroyloadMask();
			$('#treediv' + t).dialog('close');
		
		}
	};
	
	/**
	 * 默认选项
	 */
	$.fn.dictree.defaults = {
		title: "请选择",				// 弹窗标题
		width: 320,					// 宽度
	    height: 400,				// 高度
	    modal: true,				// 是否为模式窗口
	    cancel: function() {},		// 取消按钮回调函数
	    
	    checkbox: false,			// 是否多选
	    multiMax: 20,               // 多选最多选中数量
		cascadeCheck: true,			// 是否级联选择
		onlyLeafCheck: true,		// 是否仅叶子节点可选,
		cache:true,
		selectPath: false,          //是否显示选中的全路径
		selectRoot: true,           //是否显示选中的根
		pathSpliter: ',',           //全路径分隔符
		showSearch: true,           //是否显示搜索框
		useId: false,               //是否保存字典项的id
		loadFilter: function(data) {
			return $.fn.dictree.dataFilter(data);
		}
	};
	
	$.fn.acctree = function(options){
		var opts = $.extend({}, $.fn.acctree.defaults, options);
		
		return this.each(function() {    
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			$this.bind("click", function() {
				// 只读字段且不是必填字段不响应事件
				if($(this).data('readonly')){
					if(!($(this).data().validatebox && $(this).data().validatebox.options.required)){
						return;
					}
				}
				// 树形窗口元素
				var t = $.fn.dictree.getId($this);
				activeloadMask();
				if($('#treediv' + t).length == 1){
					if(o.cache==true){
						$('#treediv' + t).dialog('open');
						return;
					}else {
						destroy($('#treediv' + t));
					}
				}
				var ser = '';
				if(o.showSearch){
					ser = '<div class="modle_popinput" style="margin-top:0px;"><input value="搜索关键字" onfocus="if(this.value==\'搜索关键字\'){this.value=\'\';this.style.color=\'#2b2b2b\'}" class="modle_popinputin ac_input" name="keyword" onblur="if(this.value==\'\'){this.value=\'搜索关键字\';this.style.color=\'#aaa\'}" autocomplete="off">	</div>';
				}
				$("body").append('<div class="white_content xm_newchoosep" id="treediv' + t + '">' + ser + '<ul id="easytree' + t + '"></ul></div>');
				
				// 弹出窗口
				$('#treediv' + t).dialog({
					title: o.title,
					width: o.width,
					height: o.height,
					modal: o.modal,
					onClose: function(){
						destroyloadMask();
					},
					buttons: [{
						text: localeMsg.common.confirm,
						selected: true,
						handler: function(){
							onSelect(o, t);
						}
					}, {
						text: localeMsg.common.cancel,
						handler: function(){
							var selNode = $("#easytree" + t).tree("getSelected");
							// 取消事件回调方法
							o.cancel(selNode);
							destroyloadMask();
							$('#treediv' + t).dialog('close');
						}
					}]
				});
				
				var url = o.url;	// 请求地址
				var param = "";		// 请求参数
				if (o.param) {
					for (var key in o.param) {
						param += key + "=" + o.param[key] + "&";
					}
					param = param.lastIndexOf("&") == (param.length - 1)
							? param.substring(0, param.length - 1) : param;
					url += "?" + param;
				}
				
				
				// 初始化树
				$("#easytree" + t).tree({
					url: url,
					loadFilter: o.loadFilter,
					checkbox: o.checkbox,
					cascadeCheck: o.cascadeCheck,
					onlyLeafCheck: o.onlyLeafCheck,
					onLoadSuccess: function(node, data) {
						//设置纵向滚动条，IE8会不能出现滚动条
						$("#easytree" + t).parent().css({'overflow-y':'scroll'});
						//远程检索
						var searchUrl = url.replace('/dic/tree', '/dic/tree/search');
						var opt = {
								callback:function(data){
									var $tree = $("#easytree" + t);
									var node = $tree.tree('find', data.id);
									$tree.tree('select', node.target);
									$tree.tree('expandTo', node.target);
						}};
						autocompleteRemortDicTree($('#treediv' + t).find(":input[name=keyword]"), searchUrl, opt);
					},
					// 加载出错
					onLoadError: function(xhr, textStatus, errorThrown){
						defaultAjaxError(xhr, textStatus, errorThrown);
					},
					// 单击展开
					onClick: function(node){
						$(this).tree("expand", node.target);
					},
					// 双击选中
					onDblClick: function(node){
						var isLeaf = $("#easytree" + t).tree("isLeaf", node.target);
						// 单选只选叶子节点的情况下，不能选择非叶子节点
						if (!isLeaf && o.onlyLeafSelect) {
							return;
						}
						if(o.checkbox){
							$(this).tree("check", node.target);
						}
						onSelect(o, t);
					},
					onBeforeSelect: function(node) {
						var isLeaf = $("#easytree" + t).tree("isLeaf", node.target);
						// 单选只选叶子节点的情况下，不能选择非叶子节点
						if (!isLeaf && o.onlyLeafSelect) {
							return false;
						}
						return true;
					},
					onSelect: function(node) {
						var attr = {
								locale: node.attributes.locale,
								name: node.attributes.name,
								nameEn: node.attributes.nameEn,
								localeName: node.attributes.locale || node.attributes.localeName,
								localeNames: node.attributes.locale || node.attributes.localeName,
								zhnames: node.attributes.name || node.attributes.zhnames
						};
						// 更新选中节点属性
						$(this).tree("update", {
							target: node.target,
							attributes: addPath(this, node.target, attr, o.pathSpliter)
						});
					}
				});
			});
					
		});
		function onSelect(o, t){

			var selNode = $("#easytree" + t).tree("getSelected");
			if(selNode == null){
				selNode = {id:'',text:'',attributes:{code:'',localeNames:'',zhnames:'',ennames:''}};
			}
			if (o.pathName) {
				if (o.selectPath){
					if(o.selectRoot){
						$('input[id="'+o.pathName + '"]').val(selNode.attributes.localeNames);
					}else{
						var v = selNode.attributes.localeNames;
						if(v && v.indexOf(",") != -1){
							v = v.substring(v.indexOf(",")+1);
						}
						$('input[id="'+o.pathName + '"]').val(v);
					}
				} else {
					$('input[id="'+o.pathName + '"]').val(selNode.text);
				}
				$('input[id="'+o.pathName + '"]').attr('title',selNode.attributes.localeNames);
			}
			if (o.idName) $('input[id="'+o.idName + '"]').val(selNode.id);
			if (o.zhName) $('input[id="'+o.zhName + '"]').val(selNode.attributes.zhnames);
			if (o.enName) $('input[id="'+o.enName + '"]').val(selNode.attributes.ennames);
			
			// 确定事件回调方法
			if (o.confirm) {
				o.confirm(selNode);
			}
			$("input[name='" + o.pathName + "']").focus();
			destroyloadMask();
			$('#treediv' + t).dialog('close');
		
		}
	};
	
	/**
	 * 默认选项
	 */
	$.fn.acctree.defaults = {
		title: "请选择",				// 弹窗标题
		width: 320,					// 宽度
	    height: 400,				// 高度
	    modal: true,				// 是否为模式窗口
	    cancel: function() {},		// 取消按钮回调函数
	    
	    checkbox: false,			// 是否多选
	    multiMax: 20,               // 多选最多选中数量
		cascadeCheck: true,			// 是否级联选择
		onlyLeafSelect: true,		// 是否仅叶子节点可选,
		cache:true,
		selectPath: false,          //是否显示选中的全路径
		selectRoot: true,           //是否显示选中的根
		pathSpliter: ',',           //全路径分隔符
		showSearch: false,           //是否显示搜索框
		useId: true,               //是否保存字典项的id
		loadFilter: function(data) {
			return $.fn.acctree.dataFilter(data);
		}
	};
	$.fn.acctree.dataFilter = function(data) {
		if (data != undefined) {
			for (var i=0;i<data.length;i++) {
				// 节点附加属性
				var attributes = {};
				attributes.locale = data[i].text;
				attributes.name = data[i].textZh || data[i].text;
				attributes.nameEn = data[i].textEn || "";
				data[i].attributes = attributes;
			}
			return data;
		}
	}
	/**
	 * 数据重新封装
	 * 1.根据节点是否有子节点设置state，有为closed，无为open
	 * 2.添加节点附加属性：中文名和英文名
	 */
	$.fn.dictree.dataFilter = function(data) {
		if (data != undefined) {
			
			for (var i in data) {
				// 节点附加属性
				var attributes = {};
				attributes.locale = data[i].text || "";
				attributes.name = data[i].textZh || "";
				attributes.nameEn = data[i].textEn || "";
				attributes.code = data[i].code || "";
				// 扩展属性1, 如数据字典的编码、组织的路径名
				attributes.ext1 = data[i].ext1;
				attributes.ext2 = data[i].ext2;
				attributes.ext3 = data[i].ext3;
				attributes.ext4 = data[i].ext4;
				attributes.ext5 = data[i].ext5;
				attributes.externalCode = data[i].externalCode || "";
				attributes.outype=data[i].outype || "";
				//外部编码
				data[i].attributes = attributes;
				data[i].state = "closed";
				var children = data[i].children;
				if (children != null && children != undefined && children.length > 0) {
					// 设置state为closed
//					if (data[i].outype == "0") {
//						data[i].state = "open";
//					} else {
//						data[i].state = "closed";
//					}
					// 重新解析子节点
					var newChildren = $.fn.dictree.dataFilter(data[i].children);
					data[i].children = newChildren;
					
				} else {
					data[i].state = "open";
				}
			}
			
			return data;
		}
	};
	$.fn.dictree.getId = function($this){
		var id = $this.attr('id');
		if(id){
			return id;
		}
		id = 'id_' + (new Date()).getTime();
		$this.attr('id', id);
		return id;
	};
	function parseOUTreeType(o){
		if(o.param && o.param.type){
			if(o.param.type == '0' || o.param.type == '1'){
				o.type = 0;
			}else{
				o.type = 1;
			}
		}
	}
	// 生成选人框代码
	function genTreeHtml(t, o, $this) {
		var rightText = rightText, type = o.type;
		if(rightText == null || rightText == '') {
			rightText = '已选';
		}
		var rightTitle = type == 0 ? '姓名' : '名称';
		var rightTitle2 = type == 0 ? '所在部门' : '上级组织';
		if(o.rightTitle && o.rightTitle != ''){//通过参数指定右边标题
			rightTitle = o.rightTitle;
		}
		if(o.rightTitle2 && o.rightTitle2 != ''){//通过参数指定右边标题2
			rightTitle2 = o.rightTitle2;
		}
		var builder = new Stringbuilder();
		builder.append('<div class="white_content" id="outreediv' + t + '">');
		builder.append('<div class="modle_newchooselist xm_newchoosep">');
		builder.append('	<div class="modle_newchoosetitle"> <a href="javascript:void(0);" class="modle_newdelect">删除全部</a></div>');
		builder.append('	<div class="clean"></div>');
		builder.append('	<div class="modle_newcteams">');
		builder.append('    <div class="xm_poptabnav ofh"><div class="xm_newchooseptxt">已选</div></div>');
		builder.append('    <div><div class="modle_newdeptr2"><div class="modle_newdepname modle_newdepname2"><span class="modle_newdeptxt">');
		builder.append(rightTitle);
		builder.append('</span><span class="modle_newdeptxt">');
		builder.append(rightTitle2);
		builder.append('</span></div></div></div>');
		builder.append('    	<div class="ofh modle_newdeptrw selArea"></div>');
		builder.append('</div></div>');
		builder.append('<div class="modle_poptalkl xm_newchoosep">');
//		builder.append('	<div class="modle_popinput">');
//		builder.append('		<input onblur="if(this.value==\'\'){this.value=\'搜索关键字\';this.style.color=\'#aaa\'}" name="keyword" class="modle_popinputin"');
//		builder.append('			onfocus="if(this.value==\'搜索关键字\'){this.value=\'\';this.style.color=\'#2b2b2b\'}" value="搜索关键字" />');
//		builder.append('	</div><div class="modle_newcteams2">');
		builder.append('	<div class="modle_newcteams2">');
		builder.append('<div class="xm_poptabnav ofh"><ul>');
		var title = type == 0 ? '人员' : '组织';
		if(o.leftTitle && o.leftTitle != ''){//通过参数指定左边标题
			title = o.leftTitle;
		}
		builder.append('<li class="xm_poptabnavc"><a href="javascript:void(0);">' + title + '</a></li>');
		builder.append('</ul></div>');
		builder.append('<div class="modle_qz"><ul id="outree' + t + '" style="width:150%;"></ul>' + '</div>');
		builder.append('</div></div><div class="xm_arrowblue"></div><div class="clean"></div></div>');
		
		$("body").append(builder.toString());
		if(o.type == 0){
			var oldId = $('#' + o.idName + '').val();//已选择的人员回显
			if(oldId && oldId != ''){
				var ids = oldId.split(',');
				var names = $('#' + o.userName + '').val().split(',');
				var deptids = $('#' + o.idName + '_deptId').length > 0 ? $('#' + o.idName + '_deptId').val().split(',') : '';
				var depts = $('#' + o.idName + '_deptName').length > 0 ? $('#' + o.idName + '_deptName').val().split(',') : '';
				for ( var i = 0; i < ids.length; i++) {
					var node = {id:ids[i],text:names[i]};
					var deptId = deptids.length>0?deptids[i]:'',deptName = depts.length>0?depts[i]:'';
					genOUSelected($('#outreediv' + t), o.multi, node, deptName, deptId);
				}
			}
		}else if(o.type == 1){
			var oldId = $(':input[name=' + o.idName + ']').val();//已选择的组织回显
			if(oldId && oldId != ''){
				var ids = oldId.split(',');
				var names = $(':input[name=' + o.userName + ']').val().split(',');
				for ( var i = 0; i < ids.length; i++) {
					var node = {id:ids[i],text:names[i]};
					genOUSelected($('#outreediv' + t), o.multi, node, '');
				}
			}
		}
	}
	function getActors(param){
		var result = {};
		if(param && param.actor){
			var actors = eval('(' + param.actor + ')');
			for ( var i = 0; i < actors.length; i++) {
				var actor = actors[i];
				if(actor.actorType == '0'){//用户
					result.selectUser = true;
					if(!result.users){
						result.users = [];
					}
					result.users.push(actor);
				}else if(actor.actorType == '1'){//角色
					result.selectRole = true;
					if(!result.roles){
						result.roles = [];
					}
					result.roles.push(actor);
				}else if(actor.actorType == '2'){//组织
					result.selectOrg = true;
					if(!result.orgs){
						result.orgs = [];
					}
					result.orgs.push(actor);
				}
			}
		}
		return result;
	}
	// 生成流程选人框代码
	function genActorTreeHtml(t, rightText, param) {
		if(rightText == null || rightText == '') {
			rightText = '已选';
		}
		var ouSelector = getActors(param);
		var builder = new Stringbuilder();
		builder.append('<div class="white_content" id="actortreediv' + t + '">');
		builder.append('<div class="modle_newchooselist xm_newchoosep">');
		builder.append('	<div class="modle_newchoosetitle"> <a href="javascript:void(0);" class="modle_newdelect">删除全部</a></div>');
		builder.append('	<div class="clean"></div>');
		builder.append('	<div class="modle_newcteams">');
		builder.append('    <div class="xm_poptabnav ofh"><div class="xm_newchooseptxt">已选</div></div>');
		builder.append('    <div><div class="modle_newdeptr2"><div class="modle_newdepname modle_newdepname2"><span class="modle_newdeptxt">姓名</span><span class="modle_newdeptxt">所在部门</span></div></div></div>');
		builder.append('    	<div class="ofh modle_newdeptrw selArea"></div>');
		builder.append('</div></div>');
		builder.append('<div class="modle_poptalkl xm_newchoosep">');
		builder.append('	<div class="modle_popinput">');
		var cond = '';
		if(ouSelector.selectUser){
			builder.append('		<input  id="condition_user" class="modle_popinputin"');
			builder.append('			 />');
			cond = ' style="display:none;"';
		}
		if(ouSelector.selectRole){
			builder.append('		<input id="condition_role" class="modle_popinputin"');
			builder.append(cond);
			builder.append('/>');
			cond = ' style="display:none;"';
		}
		if(ouSelector.selectOrg){
			builder.append('		<input id="condition_org" class="modle_popinputin"');
			builder.append(cond);
			builder.append('			 />');
		}
		builder.append('	</div><div class="modle_newcteams2">');
		builder.append('<div class="xm_poptabnav ofh"><ul>');
		var clz = ' class="xm_poptabnavc"';
		if(ouSelector.selectUser){
			builder.append('<li' + clz + ' id="selUser"><a href="javascript:void(0);">人员</a></li>');
			clz = '';
		}
		if(ouSelector.selectRole){
			builder.append('<li' + clz + ' id="selRole"><a href="javascript:void(0);">角色</a></li>');
			clz = '';
		}
		if(ouSelector.selectOrg){
			builder.append('<li' + clz + ' id="selOrg"><a href="javascript:void(0);">组织</a></li>');
		}
		builder.append('</ul></div>');
		if(ouSelector.selectUser){
			builder.append('<div id="userCt"><div class="modle_newdeptr2">');
			builder.append('<div class="modle_newdepname modle_newdepname2"><span class="modle_newdepnameclass modle_newdepnameclass2">序号</span><span class="modle_newdeptxt">姓名</span><span class="modle_newdeptxt">所在部门</span></div></div>');
			builder.append('<div id="userlist" class="ofh modle_newdeptrw">');
			builder.append('</div></div>');
			if(ouSelector.selectRole){
				builder.append('<div id="roleCt" style="display:none;"><div id="rolelist" class="modle_qz"></div></div>');
			}
			if(ouSelector.selectOrg){
				builder.append('<div id="orgCt" style="display:none;" class="modle_qz"><ul id="orgtree"></ul>' + '</div>');
			}
		}else if(ouSelector.selectRole){
			builder.append('<div id="roleCt"><div id="rolelist" class="modle_qz"></div></div>');
			if(ouSelector.selectOrg){
				builder.append('<div id="orgCt" style="display:none;" class="modle_qz"><ul id="orgtree"></ul>' + '</div>');
			}
		}else if(ouSelector.selectOrg){
			builder.append('<div id="orgCt" class="modle_qz"><ul id="orgtree"></ul>' + '</div>');
		}
		builder.append('</div></div><div class="xm_arrowblue"></div><div class="clean"></div></div>');
		
		$("body").append(builder.toString());
		return ouSelector;
	}
	/**
	 * 智能搜索流程选人
	 */
	function autocompleteActor(ele, actors, o){
		ele.data('actors', actors);
		ele.autocomplete(actors, {
		 	width : o.width || 200,
		 	multiple : false,
		 	multipleSeparator : ',',
	 		result : function (event, data, formatted){
	 			if(o.callback){
	 				o.callback.call(this,data);
	 			}
		 	},
		 	max : 50,
			scroll : true,
			scrollHeight : 200,	 	
		 	formatItem : function(row) {
		 		if(o.formatItem){
		 			return formatItem.call(this,row);
		 		}else{
		 			return  row.name + '-' + row.departmentNamePath;
		 		}
			},
			formatMatch: function(row) {	
				return row.name+"_"+row.pinyin;
			},
			formatResult: function(row) {	
				if(o.formatResult){
					return o.formatResult.call(this,row);
				}
				return  row.name;
			}
		});
	}
	/**
	 * 智能搜索组织树选人
	 */
	function autocompleteUser(ele, users, o){
		ele.autocomplete(users, {
		 	width : o.width || 200,
		 	multiple : false,
		 	multipleSeparator : ',',
	 		result : function (event, data, formatted){
	 			if(o.callback){
	 				o.callback.call(this,data);
	 			}
		 	},
		 	max : 50,
			scroll : true,
			scrollHeight : 200,	 	
		 	formatItem : function(row) {
		 		if(o.formatItem){
		 			return formatItem.call(this,row);
		 		}else{
		 			return  row.text;
		 		}
			},
			formatMatch: function(row) {	
				return row.text+"_"+row.ext1;
			},
			formatResult: function(row) {	
				if(o.formatResult){
					return o.formatResult.call(this,row);
				}
				return  (row.text);
			}
		});
	}
	/**
	 * 远程智能搜索选人
	 */
	function autocompleteRemortUser(ele, users, o){
		ele.autocomplete(users, {
		 	width : o.width || 200,
		 	multiple : false,
		 	multipleSeparator : ',',
	 		result : function (event, data, formatted){
	 			var obj = eval('(' + data + ')')
	 			if(o.callback){
	 				o.callback.call(this,obj);
	 			}
		 	},
		 	max : 50,
			scroll : true,
			scrollHeight : 200,	 	
		 	formatItem : function(row) {
		 		var obj = eval('(' + row + ')')
		 		if(o.formatItem){
		 			return formatItem.call(this,obj);
		 		}else{
		 			return  obj.name + '-' + obj.departmentNamePath;
		 		}
			},
			formatMatch: function(row) {
				var obj = eval('(' + row + ')')
				return obj.name+"_"+obj.username+"_"+obj.pinyin;
			},
			formatResult: function(row) {	
				var obj = eval('(' + row + ')')
				if(o.formatResult){
					return o.formatResult.call(this,obj);
				}
				return obj.name;
			}
		});
	}
	/**
	 * 远程检索多级字典项
	 */
	function autocompleteRemortDicTree(ele, users, o){
		ele.autocomplete(users, {
		 	width : o.width || 200,
		 	multiple : false,
		 	multipleSeparator : ',',
		 	matchCase : true,
	 		result : function (event, data, formatted){
	 			var obj = eval('(' + data + ')')
	 			if(o.callback){
	 				o.callback.call(this,obj);
	 			}
		 	},
		 	max : 50,
			scroll : true,
			scrollHeight : 200,	 	
		 	formatItem : function(row) {
		 		var obj = eval('(' + row + ')')
		 		if(o.formatItem){
		 			return formatItem.call(this,obj);
		 		}else{
		 			return  obj.text;
		 		}
			},
			formatMatch: function(row) {
				var obj = eval('(' + row + ')')
				return obj.text+"_"+obj.code;
			},
			formatResult: function(row) {	
				var obj = eval('(' + row + ')')
				if(o.formatResult){
					return o.formatResult.call(this,obj);
				}
				return obj.text;
			}
		});
	}
	function bindDeleteSelectedEvent(dlg, o){
		//删除全部已选择
		dlg.find(".modle_newchoosetitle .modle_newdelect").unbind().bind('click', function(){
			dlg.find(".selArea").find(".modle_newdeptr").remove();
		});
		//删除单条已选择
		$(".modle_newdeptr .modle_newdepclose").on('click', function(){
			$(this).parent().parent().remove();
		});
	}
	/**
	 * 流程选人的事件绑定
	 */
	function bindActorEvent(dlg, o, actorSelector){
		var inited = false;
		if(actorSelector.selectUser){//配置了人员
			$('#selUser').unbind().bind('click', function(){
				$(this).addClass('xm_poptabnavc').siblings().removeClass('xm_poptabnavc');
				$('#userCt').show();
				$('#condition_user').show();
				$('#roleCt').hide();
				$('#condition_role').hide();
				$('#orgCt').hide();
				$('#condition_org').hide();
				if(!$(this).data('list')){
					var $this = $(this);
					var data = o.param;
					data.type = 0;//参数0是人员
					$.ajax({
						type : "post",
						url : o.url,
						data : data,
						dataType : "json",
						success : function(json) {
							var builder = new Stringbuilder();
							for ( var i = 0; i < json.length; i++) {
								var u = json[i];
								builder.append('<div userid="');
								builder.append(u.id);
								builder.append('" name="');
								builder.append(u.name);
								builder.append('" depart="');
								builder.append(o.showDepartmentPath ? u.departmentNamePath : u.departmentName);
								builder.append('" class="modle_newdeptr"><div class="modle_newdepname modle_newdepname2"><span class="modle_newdepnameclass">');
								builder.append(i+1);
								builder.append('</span><span class="modle_newdeptxt">');
								builder.append(u.name);
								builder.append('</span><span class="modle_newdeptxt2">');
								builder.append(o.showDepartmentPath ? u.departmentNamePath : u.departmentName);
								builder.append('</span></div></div>');
							}
							$('#userlist').append(builder.toString());
							$('#userlist').find('div.modle_newdeptr').bind('click', function(){//添加单个人员
								$(this).addClass('modle_namelistinon').siblings().removeClass('modle_namelistinon');
								genActorSelected(dlg, o.multi, $(this).attr('userid'), $(this).attr('name'),$(this).attr('depart'));
							});
							$this.data('list', json);
							var opt = {callback:function(data){
								genActorSelected(dlg, o.multi, data.id, data.name, data.departmentNamePath);
							}};
							autocompleteActor($("#condition_user"), json, opt);//智能检索
						}
					});
				}
			});
			$('#selUser').click();
			inited = true;
		}
		if(actorSelector.selectRole){//配置了角色
			$('#selRole').unbind().bind('click', function(){
				$(this).addClass('xm_poptabnavc').siblings().removeClass('xm_poptabnavc');
				$('#userCt').hide();
				$('#condition_user').hide();
				$('#roleCt').show();
				$('#condition_role').show();
				$('#orgCt').hide();
				$('#condition_org').hide();
				if(!$(this).data('list')){
					var $this = $(this);
					var data = o.param;
					data.type = 1;//参数1是角色
					$.ajax({
						type : "post",
						url : o.url,
						data : data,
						dataType : "json",
						success : function(json) {
							var alluser = [], userset = {};
							var builder = new Stringbuilder();
							for ( var i = 0; i < json.length; i++) {
								var role = json[i].role;
								var users = json[i].users;
								builder.append('<div class="modle_talkdown" id="');
								builder.append(role.id);
								builder.append('">');
								builder.append(role.value);
								builder.append('<em class="modle_add"></em></div>');
								if(users && users.length > 0){
									builder.append('<div class="modle_myteam">');
									for ( var j = 0; j < users.length; j++) {
										var u = users[j];
										if(!userset[u.id]){
											userset[u.id] = u.id;
											alluser.push(u);
										}
										builder.append('<div userid="');
										builder.append(u.id);
										builder.append('" name="');
										builder.append(u.name);
										builder.append('" depart="');
										builder.append(o.showDepartmentPath ? u.departmentNamePath : u.departmentName);
										builder.append('" class="modle_namelistin modle_namelistin2">');
										builder.append(u.name);
										builder.append(' - ');
										builder.append(o.showDepartmentPath ? u.departmentNamePath : u.departmentName);
										builder.append('</div>');
									}
									builder.append('</div>');
								}
							}
							$('#rolelist').append(builder.toString());
							$('#rolelist').find('div.modle_namelistin2').bind('click', function(){//添加单个人员
								$('#rolelist').find('div.modle_namelistin2').removeClass('modle_namelistinon');
								$(this).addClass('modle_namelistinon');
								genActorSelected(dlg, o.multi, $(this).attr('userid'), $(this).attr('name'),$(this).attr('depart'));
							});
							$('#rolelist').find('.modle_add').bind('click', function(){//添加角色下所有人员
								var roleid = $(this).parent().attr('id');
								var data = $this.data('list');
								for ( var i = 0; i < data.length; i++) {
									if(data[i].role.id == roleid){
										var users = data[i].users;
										if(o.multi){
											for ( var j = 0; j < users.length; j++) {
												var u = users[j];
												genActorSelected(dlg, o.multi, u.id, u.name, u.departmentNamePath);
											}
										}else if(users.length > 0){
											var u = users[0];
											genActorSelected(dlg, o.multi, u.id, u.name, u.departmentNamePath);
										}
										break;
									}
								}
								return false;
							});
							$('#rolelist').find('.modle_talkdown').bind('click', function(){//展开/折叠
								if($(this).next('.modle_myteam').is(':visible')){
									$(this).addClass('modle_talkup');
									$(this).next('.modle_myteam').hide();
								}else{
									$(this).removeClass('modle_talkup');
									$(this).next('.modle_myteam').show();
								}
							});
							$this.data('list', json);
							var opt = {callback:function(data){
								genActorSelected(dlg, o.multi, data.id, data.name, data.departmentNamePath);
							}};
							autocompleteActor($("#condition_role"), alluser, opt);//智能检索
						}
					});
				}
			});
			if(inited == false){
				$('#selRole').click();
				inited = true;
			}
		}
		if(actorSelector.selectOrg){//配置了组织
			$('#selOrg').unbind().bind('click', function(){
				$(this).addClass('xm_poptabnavc').siblings().removeClass('xm_poptabnavc');
				$('#userCt').hide();
				$('#condition_user').hide();
				$('#roleCt').hide();
				$('#condition_role').hide();
				$('#orgCt').show();
				$('#condition_org').show();
				if(!$(this).data('list')){
					var $this = $(this);
					var data = o.param;
					data.type = 2;//参数2是组织
					o.loader = function(param,success,error){
						$.ajax({
							type : "post",
							url :  o.url,
							data : data,
							dataType : "json",
							success : function(json) {
								success(json);
							}
						});
					};
					// 单击展开
					o.onClick = function(node){
						$(this).tree("expand", node.target);
					};
					o.onBeforeSelect = function(node) {
						var children = $(this).tree("getChildren", node.target);
						if ((children && children.length > 0) || node.attributes.outype != '9') {
							return false;
						}
					};
					// 选中事件
					o.onSelect = function(node) {
						var parent = $(this).tree("getParent", node.target);
						genActorSelected(dlg, o.multi, node.id, node.text, parent.text);
					};
					// 加载成功
					o.onLoadSuccess = function(node, data) {
						$this.data('list', data);
						o.type = 0;
						var ous = $.fn.outree.autocompleteData(o, data);
						if(ous.length > 0){
							var opt = {callback:function(data){
								var node = $('#orgtree').tree('find', data.id);
								if(node){
									$('#orgtree').tree('select', node.target);
									$('#orgtree').tree("expandTo", node.target);
									var parent = $('#orgtree').tree("getParent", node.target);
									genActorSelected(dlg, o.multi, node.id, node.text, parent.text);
								}
							}};
							autocompleteUser($("#condition_org"), ous, opt);
						}
					};
					// 加载出错
					o.onLoadError = function(xhr, textStatus, errorThrown){
						defaultAjaxError(xhr, textStatus, errorThrown);
					};
					$('#orgtree').tree(o);	
				}
			});
			if(inited == false){
				$('#selOrg').click();
			}
		}
		
	}
	function buildParam(param) {
		var ids = param.id.split(",");
		param.actor = new Array();
		for (var i in ids) {
			
		}
	}
	
	/**
	 * 生成已选节点信息
	 * id 已选节点id
	 * text 已选节点名称
	 * parent 已选节点的父节点名称
	 */
	function genSelected(id, text, parent) {
		if ($("input[name='selectedItem'][value='" + id + "']").length < 1) {
			var sb = new Stringbuilder();
			sb.append('<div class="modle_newdeptr"><input type="hidden" name="selectedItem" value="' + id + '" />');
			sb.append('  <a href="javascript:void(0);" class="modle_newdepclose"></a>');
			sb.append('  <div class="modle_newdepname">' + text + '<span class="modle_newdeptxt">' + parent + '</span></div></div>');
			$("#selArea").append(sb.toString());
		}
	}
	function genOUSelected(dlg, multi, node, parent,parentId) {
		var id = node.id,text=node.text;
		if(multi){
			if (dlg.find("input[name='selectedItem'][value='" + id + "']").length < 1) {
				var sb = new Stringbuilder();
				sb.append('<div class="modle_newdeptr"><input type="hidden" actor="' + text + '" name="selectedItem" value="' + id + '" />');
				sb.append('<div class="modle_newdepname modle_newdepname2"><a href="javascript:void(0);" class="modle_newdepclose"></a>');
				sb.append('<span class="modle_newdeptxt">' + text + '</span><span class="modle_newdeptxt2">' + parent + '</span></div>');
				sb.append('<input type="hidden" name="selectedDepartId" value='+parentId+'>');
				sb.append('<input type="hidden" name="selectedDepartName" value='+parent+'></div>');
				dlg.find(".selArea").append(sb.toString());
				dlg.find("input[name='selectedItem'][value='" + id + "']").data('node', node);
			}
		}else{
			if (dlg.find("input[name='selectedItem'][value='" + id + "']").length < 1) {
				dlg.find(".selArea").find(".modle_newdeptr").remove();
				var sb = new Stringbuilder();
				sb.append('<div class="modle_newdeptr"><input type="hidden" actor="' + text + '" name="selectedItem" value="' + id + '" />');
				sb.append('<div class="modle_newdepname modle_newdepname2"><a href="javascript:void(0);" class="modle_newdepclose"></a>');
				sb.append('<span class="modle_newdeptxt">' + text + '</span><span class="modle_newdeptxt2">' + parent + '</span></div>');
				sb.append('<input type="hidden" name="selectedDepartId" value="'+parentId+'">');
				sb.append('<input type="hidden" name="selectedDepartName" value="'+parent+'"></div>');
				dlg.find(".selArea").append(sb.toString());
				dlg.find("input[name='selectedItem'][value='" + id + "']").data('node', node);
			}
		}
	}
	function genActorSelected(dlg, multi, id, text, parent) {
		if(multi){
			if (dlg.find("input[name='selectedItem'][value='" + id + "']").length < 1) {
				var sb = new Stringbuilder();
				sb.append('<div class="modle_newdeptr"><input type="hidden" actor="' + text + '" name="selectedItem" value="' + id + '" />');
				sb.append('<div class="modle_newdepname modle_newdepname2"><a href="javascript:void(0);" class="modle_newdepclose"></a>');
				sb.append('<span class="modle_newdeptxt">' + text + '</span><span class="modle_newdeptxt2">' + parent + '</span></div></div>');
				dlg.find(".selArea").append(sb.toString());
			}
		}else{
			if (dlg.find("input[name='selectedItem'][value='" + id + "']").length < 1) {
				dlg.find(".selArea").find(".modle_newdeptr").remove();
				var sb = new Stringbuilder();
				sb.append('<div class="modle_newdeptr"><input type="hidden" actor="' + text + '" name="selectedItem" value="' + id + '" />');
				sb.append('<div class="modle_newdepname modle_newdepname2"><a href="javascript:void(0);" class="modle_newdepclose"></a>');
				sb.append('<span class="modle_newdeptxt">' + text + '</span><span class="modle_newdeptxt2">' + parent + '</span></div></div>');
				dlg.find(".selArea").append(sb.toString());
			}
		}
	}
	
	// 删除已选节点
	function removeSelected($tree) {
		$(".modle_newdeptr .modle_newdepclose").unbind("click");
		$(".modle_newdeptr .modle_newdepclose").click(function(){
			var nodeId = $(this).siblings("input[name='selectedItem']").val();
			var checkedNode = $tree.tree("find", nodeId);
			$tree.tree("uncheck", checkedNode.target);
			$(this).parent().remove();
		});
	}
	// 删除所有已选节点
	function removeAll($tree) {
		$(".modle_newchoosetitle .modle_newdelect").unbind("click");
		$(".modle_newchoosetitle .modle_newdelect").click(function(){
			var root = $tree.tree("getRoot");
			$tree.tree("uncheck", root.target);
			$(".modle_newdeptr").remove();
		});
	}
	
	// 获取已选节点
	function getChecked($tree, node, checked) {
		var parent = node;
		var nodes = new Array();
		if ($tree.tree("isLeaf", node.target) && $tree.tree("getParent", node.target) != null) {
			parent = $tree.tree("getParent", node.target);
			nodes.push(node);
		} else {
			nodes = $tree.tree("getChildren", node.target);
		}
		if (checked) {
			for (var i in nodes) {
				// ie下会多一个undefined项
				if ($tree.tree("isLeaf", nodes[i].target) && nodes[i].id != undefined && nodes[i].attributes.outype=='9') {
					genSelected(nodes[i].id, nodes[i].text, parent.text);
				}
			}
			// 绑定删除单个人员按钮
			removeSelected($tree);
			// 绑定删除全部人员按钮
			removeAll($tree);
			
		} else {
			for (var i in nodes) {
				$("input[name='selectedItem'][value='" + nodes[i].id + "']").parent().remove();
			}
		}
	}
	/**
	 * 组织用户树，用于选人和组织
	 */
	$.fn.outree = function(options){
		var opts = $.extend({}, $.fn.outree.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			var _e = function() {
				// 只读字段不响应事件
				if($(this).data('readonly')){
					if(!($(this).data().validatebox && $(this).data().validatebox.options.required)){
						return;
					}
				}
				activeloadMask();
				// 树形窗口元素
				var t = $.fn.dictree.getId($this);
				if($('#outreediv' + t).length == 1){
					if(o.cache==true){
						$('#outreediv' + t).dialog('open');
						return;
					}else {
						destroy($('#outreediv' + t));
					}
				}
				if(o.checkbox == true){
					o.multi = true;
					o.checkbox = false;
				}
				//解析类型，是选择人员还是组织
				parseOUTreeType(o);
				// 生成html
				genTreeHtml(t, o, $this);
				
				// 弹出窗口
				$('#outreediv' + t).dialog({
					title: o.title,
					width: o.width,
					height: o.height,
					modal: o.modal,
					onClose: function(){
						if(o.hideMaskOnClose){
							destroyloadMask();
						}
					},
					buttons: [{
						text: "确定",
						selected: true,
						handler: function(){
							var param = {};
							var text = "";
							var id = "";
							var nodes = null;
							var sapId = "",idCard="";
							var departmentId = "";
							var departmentName = "";
							if (o.multi) {
								// 多选
								nodes = new Array();
								var items = $('#outreediv' + t).find(':input[name=selectedItem]');
								var selectedDepartmengId  = $('#outreediv' + t).find(':input[name=selectedDepartId]');
								var selectedDepartmengName  = $('#outreediv' + t).find(':input[name=selectedDepartName]');
								if(items.length > o.multiMax){
									common.showTip({text:'选择数量不能超过' + o.multiMax + '个'});
									return;
								}
								for ( var i = 0; i < items.length; i++) {
									var item = $(items[i]);
									text += item.attr('actor') + ",";
									id += item.val() + ",";
									sapId += item.data('node').ext2 + ",";
									idCard += item.data('node').ext3 + ",";
									departmentId += $(selectedDepartmengId[i]).val()+ ",";
									departmentName += $(selectedDepartmengName[i]).val()+ ",";
									nodes.push(item.data('node'));
								}
								text = text.lastIndexOf(",") == text.length - 1
										? text.substring(0, text.length - 1) : text;
								id = id.lastIndexOf(",") == id.length - 1
										? id.substring(0, id.length - 1) : id;
								departmentId = departmentId.lastIndexOf(",") == departmentId.length - 1
										? departmentId.substring(0, id.length - 1) : departmentId;
										departmentName = departmentName.lastIndexOf(",") == departmentName.length - 1
										? departmentName.substring(0, id.length - 1) : departmentName;
							} else {
								// 单选
								var item = $('#outreediv' + t).find(':input[name=selectedItem]');
								var selectedDepartmengId  = $('#outreediv' + t).find(':input[name=selectedDepartId]');
								var selectedDepartmengName  = $('#outreediv' + t).find(':input[name=selectedDepartName]');
								if(item.length > 0){
									text = item.attr('actor');
									id = item.val();
									nodes = item.data('node');
									sapId = nodes.ext2;
									idCard = nodes.ext3;
									departmentId = $(selectedDepartmengId).val();
									departmentName = $(selectedDepartmengName).val();
								}
							}
							// 确定事件回调方法
							if (o.confirm) {
								if(!o.multi && nodes == null){
									nodes = {attributes:{ext1:''},text:''};
								}
								param.nodes = nodes;
								param.text = text;
								param.id = id;
								param.sapId = sapId;
								param.idCard = idCard;
								param.departmentId = departmentId;
								param.departmentName = departmentName;
								o.confirm(param);
							} else {
								$("#" + o.userName).val(text);
								$("#" + o.idName).val(id);
								$("input[name='" + o.userName + "']").val(text);
								$("input[name='" + o.idName + "']").val(id);
								$("#" + o.idName + "_deptId").val(departmentId);
								$("#" + o.idName + "_deptName").val(departmentName);
							}
							if(o.hideMaskOnClose){
								destroyloadMask();
							}
							$('#outreediv' + t).dialog('close');
							$("input[name='" + o.userName + "']").focus();
						}
					}, {
						text: "取消",
						handler: function(){
							if(o.hideMaskOnClose){
								destroyloadMask();
							}
							$('#outreediv' + t).dialog('close');
							$("input[name='" + o.userName + "']").focus();
						}
					}]
				});
				bindDeleteSelectedEvent($('#outreediv' + t), o);
				if($this.data('selected')){//已选中的人员放在输入框的jquery的data中，通过js设置的
					o.param.selIds = $this.data('selected');
					o.cache = false;//取消缓存
					o.canSelectRoot = true;//可以选择根节点
				}else if(o.selected){
					o.param.selIds = o.selected;
				}
				if($this.data('orgId')){//已选中的组织id放在输入框的jquery的data中，通过js设置的
					o.param.orgId = $this.data('orgId');
				}else if(o.orgId){
					o.param.orgId = o.orgId;
				}
				// 封装带参数的请求地址
				o.url = o.url.split("?")[0];
				o.url = buildUrl(o.url, o.param);
				
				if(o.type == 0){
					o.loadFilter = function(data){
						return $.fn.outree.asyncDataFilter(data);
					};
					var searchUrl = baseURL + '/orgUser/tree/searchuser';
					var opt = {
							callback:function(data){
								var node = {id:data.id,text:data.name,ext2:data.sapId,ext3:data.idCard};
								genOUSelected($('#outreediv' + t), o.multi, node, data.departmentName, data.departmentId);
					}};
					autocompleteRemortUser($('#outreediv' + t).find(":input[name=keyword]"), searchUrl, opt);
				}
				// 单击展开
				o.onClick = function(node){
					$(this).tree("expand", node.target);
				};
				// 单选仅可选择叶子节点
				o.onBeforeSelect = function(node) {
					var isLeaf = $("#outree" + t).tree("isLeaf", node.target);
					
					// 单选只选叶子节点的情况下，不能选择非叶子节点
					if (!isLeaf && o.onlyLeafSelect) {
						return false;
					}
					if(o.type == 0){
						if(node.attributes.outype != 9){
							return false;
						}
					}
					return true;
				};
				// 选中事件
				o.onSelect = function(node) {

					//控制不能选择根节点
					if(!o.canSelectRoot){
						var rootNode = $("#outree" + t).tree("getRoot");
						var selectedNode = $("#outree" + t).tree("getSelected");
						
						if(null != selectedNode){
							if(rootNode.id == selectedNode.id){
								return ;
							}
						}
					}
					var parent = $(this).tree("getParent", node.target);
					genOUSelected($('#outreediv' + t), o.multi, node, parent ? parent.text : '',parent?parent.id:'');
				};
				// 加载成功
				o.onLoadSuccess = function(node, data) {
					if(o.type > 0){
						var id = $("input[name='" + o.idName + "']").val();
						var ous = $.fn.outree.autocompleteData(o, data);
						if(ous.length > 0){
							var opt = {
									callback:function(data){
										var $tree = $("#outree" + t);
										var node = $tree.tree('find', data.id);
										if(node){
											$tree.tree('select', node.target);
											$tree.tree("expandTo", node.target);
											var parent = $tree.tree("getParent", node.target);
											genOUSelected($('#outreediv' + t), o.multi, node, parent.text);
										}
							}};
//							autocompleteUser($('#outreediv' + t).find(":input[name=keyword]"), ous, opt);
						}
					}
				};
				// 加载出错
				o.onLoadError = function(xhr, textStatus, errorThrown){
					defaultAjaxError(xhr, textStatus, errorThrown);
				};
				// 初始化树
				$("#outree" + t).tree(o);
				
			};
			
			if(o.event != "none") {
				$this.bind(o.event, _e);
			} else {
				_e.call();
			}
					
		});
		
	};
	//param的type： 0:人员，1：角色，2：部门，3：公司，4：菜单，5：公司及部门
	$.fn.outree.defaults = {
		title: "请选择",				// 弹窗标题
		width: 620,					// 宽度
	    height: 490,				// 高度
	    modal: true,				// 是否为模式窗口
	    cancel: function() {},		// 取消按钮回调函数
	    event: "click",				// 绑定事件
	    type: 0,                    //选择类型，0：人员，1：组织
	    multi: false,			// 是否多选
	    multiMax: 100,			// 多选最多选择数量
		cascadeCheck: true,			// 是否级联选择
		onlyLeafSelect: true,		// 是否仅叶子节点可选
		cache: true,                // 是否缓存
		leftTitle: null,            //左侧选择框标题
		rightTitle: null,           //右侧已选框标题
		rightTitle2: null,          //右侧已选框上级标题
		hideMaskOnClose: true,      //关闭对话框时是否去掉遮罩，默认true
		loadFilter: function(data) {
			return $.fn.dictree.dataFilter(data);
		}
	};
	$.fn.outree.asyncDataFilter = function (data) {
	  if (data != undefined) {
	      for (var i=0;i < data.length; i++) {
	    	  var attributes = {};
	    	  attributes.outype=data[i].outype || "";
	    	  data[i].attributes = attributes;
	    	  if(data[i].outype == 9){
			    data[i].state = 'open';
			    data[i].children = [];
	    	  }
		  }     
        }
        return data;
	};
	//从tree响应的json中解析数据供autocomplete使用
	$.fn.outree.autocompleteData = function(o, data){
		var result = [];
		if(o.type == 0){
			for ( var i = 0; i < data.length; i++) {
				if(data[i].outype == 9){
					result.push(data[i]);
				}
				var children = data[i].children;
				if (children != null && children != undefined && children.length > 0) {
					var newchildren = $.fn.outree.autocompleteData(o, children);
					if(newchildren.length > 0){
						result = result.concat(newchildren);
					}
				}
			}
		}else{
			for ( var i = 0; i < data.length; i++) {
				if(data[i].outype != 9){
					result.push(data[i]);
				}
				var children = data[i].children;
				if (children != null && children != undefined && children.length > 0) {
					var newchildren = $.fn.outree.autocompleteData(o, children);
					if(newchildren.length > 0){
						result = result.concat(newchildren);
					}
				}
			}
		}
		return result;
	};
	/**
	 * 流程选人树
	 */
	$.fn.actortree = function(options){
		var opts = $.extend({}, $.fn.actortree.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			var _e = function() {
				// 树形窗口元素
				var t = (new Date()).getTime();
				// 生成html
				var actorSelect = genActorTreeHtml(t, o.rightText, o.param);
				// 弹出窗口
				$('#actortreediv' + t).dialog({
					title: o.title,
					width: o.width,
					height: o.height,
					modal: o.modal,
					onClose: function(){
						destroy($(this));
					},
					buttons: [{
						text: "确定",
						selected: true,
						handler: function(){
							var param = {};
							var text = "";
							var id = "";
							var actors = new Array();
							if (o.multi) {
								// 多选
								var items = $('#actortreediv' + t).find(':input[name=selectedItem]');
								for ( var i = 0; i < items.length; i++) {
									var item = $(items[i]);
									text += item.attr('actor') + ",";
									id += item.val() + ",";
									var actor = {};
									actor.actorName = item.attr('actor');
									actor.actorId = item.val();
									actors.push(actor);
								}
								text = text.lastIndexOf(",") == text.length - 1
										? text.substring(0, text.length - 1) : text;
								id = id.lastIndexOf(",") == id.length - 1
										? id.substring(0, id.length - 1) : id;
							} else {
								// 单选
								var item = $('#actortreediv' + t).find(':input[name=selectedItem]');
								if(item.length > 0){
									text = item.attr('actor');
									id = item.val();
									var actor = {};
									actor.actorName = text;
									actor.actorId = id;
									actors.push(actor);
								}
							}
							// 确定事件回调方法
							if (o.confirm) {
								if(text == ""){
									text = null;
								}
								if(id == ""){
									id = null;
									common.showTip({title: localeMsg.common.prompt, text: '请选择待办人员'});
									return;// 没选人禁止确定
								}
								param.text = text;
								param.id = id;
								param.actors = actors;
								o.confirm(param);
							} else {
								$("input[name='" + o.userName + "']").val(text);
								$("input[name='" + o.idName + "']").val(id);
							}
							destroy("#actortreediv" + t);
							$("input[name='" + o.userName + "']").focus();
						}
					}, {
						text: "取消",
						handler: function(){
							destroy("#actortreediv" + t);
							$("input[name='" + o.userName + "']").focus();
						}
					}]
				});
				// 封装带参数的请求地址
				o.url = o.url.split("?")[0];
				
				bindActorEvent($("#actortreediv" + t), o, actorSelect);
				bindDeleteSelectedEvent($("#actortreediv" + t), o);
			};
			
			if(o.event != "none") {
				$this.bind(o.event, _e);
			} else {
				_e.call();
			}
					
		});
		
	};
	
	$.fn.actortree.defaults = {
		title: "请选择",				// 弹窗标题
		width: 620,					// 宽度
	    height: 490,				// 高度
	    modal: true,				// 是否为模式窗口
	    cancel: function() {},		// 取消按钮回调函数
	    event: "click",				// 绑定事件
	    
	    multi: false,			// 是否多选
		cascadeCheck: true,			// 是否级联选择
		onlyLeafCheck: false,		// 是否仅叶子节点可选
		showDepartmentPath: true,         // 是否显示部门全路径（例如安徽设计公司,综合部），否则显示部门名称（例如综合部）
		loadFilter: function(data) {
			return $.fn.dictree.dataFilter(data);
		}
	};
	/**
	 * 组织用户树
	 */
	$.fn.newtree = function(options){
		var opts = $.extend({}, $.fn.outree.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			// 树形窗口元素
			var t = (new Date()).getTime();
			$this.append('<ul id="outree' + t + '"></ul>');
			
			// 封装带参数的请求地址
			o.url = o.url.split("?")[0];
			o.url = buildUrl(o.url, o.param);
			
			o.onBeforeSelect = function(node) {
				var children = $(this).tree("getChildren", node.target);
				// 单选只选叶子节点的情况下，不能选择非叶子节点
				if (children && children.length > 0 && o.onlyLeafSelect) {
					return false;
				}
			};
			o.onDblClick = o.onDbClick || function(node) {
				$(this).tree('beginEdit',node.target);
			},
			o.onAfterEdit = o.saveEdit;
			
			// 初始化树
			$("#outree" + t).tree(o);
					
		});
		
	};
	
	/**
	 * 提示框，可设置延时时间自动关闭 
	 */
	$.fn.showTip = function(options){
		var opts = $.extend({}, $.fn.showTip.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
//			$this.bind(o.event, function(){
				$("body").append('<div id="dialogdiv">' + o.text + '</div>');
				
				// 弹出窗口
				$('#dialogdiv').dialog({
					title: o.title,
					width: o.width,
					height: o.height,
					modal: o.modal,
					buttons: [{
						text: "确定",
						handler: function(){
							destroy("#dialogdiv");
						}
					}]
				});
				
				// 延时自动关闭
				setTimeout(function(){destroy("#dialogdiv");}, o.timeout);
			});
//		});
	};
	
	$.fn.showTip.defaults = {
		title: "提示",
		width: 240,
		height: 180,
		modal: true,
		event: "click",
		text: "提示内容",
		timeout: 1500
	};
	
	$.fn.table = function(options){
		var opts = $.extend({}, $.fn.showTip.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			$this.datagrid({
				
			});
		});
	};
	
	/**
	 * 自动填充，使用autocomplete 1.1
	 * options = {
	 * 		url : url,
	 * 		param : param,
	 * 		callback : function(data){},
	 * 		formatItem : formatItem(row){},
	 * 		formatResult : formatResult(row){}
	 * }
	 */
	$.fn.autosearch = function(options) {
		var opts = $.extend({}, $.fn.showTip.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			$.ajax({
				type : "post",
				url : o.url,
				data : o.param,
				dataType : "json",
				success : function(json) {
					$this.autocomplete(json, {
					 	width : o.width || 200,
					 	multiple : o.multiple || false,
					 	multipleSeparator : ',',
				 		result : function (event, data, formatted){
				 			if(o.callback){
				 				o.callback.call(this,data);
				 			}
					 	},
					 	max : 10,
						scroll : true,
						scrollHeight : 200,	 	
					 	formatItem : function(row) {
					 		if(o.formatItem){
					 			return formatItem.call(this,row);
					 		}else{
					 			return  row.text;
					 		}
						},
						formatMatch: function(row) {	
							return row.text+"_"+row.ext1;
						},
						formatResult: function(row) {	
							if(o.formatResult){
								return o.formatResult.call(this,row);
							}
							return  (row.text);
						}
					});
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
			    	var resp=XMLHttpRequest.responseText;
					if("417"==XMLHttpRequest.status){
						var json=JSON.parse(resp); 				
						alert(json.error);
					} else {
					}
					if(failure && failure!=undefined){
						failure.call(this);
					}
			    }
			});
		});
	};
	
	/**
	 * 功能:列表全清、全选
	 * 参数:options = {
	 * 		itemName : "name",
	 * 		callback : function(objects){}
	 * }
	 * 案例:$("#checkall").checkall({itemName:"id"});
	 */
	$.fn.checkall = function(options){
		var defaults = {itemName:"id", callback:null},
			options = $.extend(defaults, options),
			$obj = $(this),
			$items = $("input[name='"+options.itemName+"']");
//		$items.on('click',function(){
		$(document).on('click',"input[name='"+options.itemName+"']",function(){
			if($items.filter(":checked").length === $items.length){
				$obj.prop("checked",true);
			}else{
				$obj.removeAttr("checked");
			}
			if(typeof options.callback === "function") options.callback($items.filter(":checked"));
		});
		return $obj.each(function(){
			$(document).on('click','#' + $obj.attr("id"),function(){
				if($obj.is(":checked")){
					$items.prop("checked", true);
				}else{
					$items.removeAttr("checked");
				}
				if(typeof options.callback === "function") options.callback($items.filter(":checked"));
			});
		});
	};
	
	$.fn.chart = function(options){
		var defaults = {
			url : baseURL + "/",
			callback:null
		};
		options = $.extend(defaults, options);
		var $obj = $(this);
		return $obj.each(function(){
			$.ajax({
				type : "get",
				url : baseURL + "/test/chart",
				dataType : "json",
				success :function(json) {
				    $('#container').highcharts({
				    	chart: {
				    		type: 'spline',
				            animation: Highcharts.svg, // don't animate in old IE
				            marginRight: 10,
				            events: {
				                load: function () {
				                    // set up the updating of the chart each 5 seconds
				                    var seriesArr = this.series;
				                    setInterval(function () {
				                    	$.ajax({
				                    		type : "get",
				                    		url : baseURL + "/test/updated",
				                    		dataType : "json",
				                    		success :function(json) {
				                    			var updateData = json.dataset;
				                    			var xNames = json.categories;
						                    	for (var i = 0; i < seriesArr.length; i++) {
						    	                    var series = seriesArr[i];
							                        var x = xNames[i];
							                        var yDatas = updateData[i].data;
						    	                    for (var j = 0; j < yDatas.length; j++) {
								                        var y = yDatas[j];
								                        series.addPoint([x, y], true, true);
						    	                    }
						                    	}
				                    		}
				                    	});
				                    }, 5000);
				                }
				            },
				            zoomType : "x"
				    	},
				        title: {
				            text: "Pool Read",
				            x: -20 //center
				        },
				        xAxis: {
				            categories: json.categories,
				            tickInterval: 60
				        },
				        yAxis: {
				            title: {
				                text: 'Bytes Per Second'
				            },
				            plotLines: [{
				                value: 0,
				                width: 1,
				                color: '#808080'
				            }]
				        },
				        /* tooltip: {
				            valueSuffix: '°C'
				        }, */
				        legend: {
				            borderWidth: 0
				        },
				        series: json.dataset
				    });
				}
			});
		});
	};
	
	/**
	 * 关闭弹窗
	 */
	function destroy(obj) {
		$(obj).dialog("destroy");
		$(obj).remove();
	}
	
	/**
	 * 添加节点的路径属性
	 */
	function addPath(tree, target, attr, spliter) {
		var parent = $(tree).tree("getParent", target);
		if (parent) {
			if(spliter == undefined){
				spliter = ',';
			}
			attr.codes = parent.attributes.ext1 + spliter + attr.codes;
			attr.localeNames = parent.attributes.locale + spliter + attr.localeNames;
			attr.zhnames = parent.attributes.name + spliter + attr.zhnames;
			attr.ennames = parent.attributes.nameEn + spliter + attr.ennames;

			addPath(tree, parent.target, attr, spliter);
		}
		
		return attr;
	}
	
	function addCheckPath(tree, target, attr, spliter) {
		var parent = $(tree).tree("getParent", target);
		if (parent) {
			if(spliter == undefined){
				spliter = ',';
			}
			attr.codes = parent.attributes.ext1 + spliter + attr.codes;
			attr.localeNames = parent.attributes.locale + spliter + attr.localeNames;
			attr.zhnames = parent.attributes.name+ spliter + attr.zhnames;
			attr.ennames = parent.attributes.nameEn + spliter + attr.ennames;

			addPath(tree, parent.target, attr, spliter);
		}
		
		return attr;
	}
	/**
	 * 封装请求参数
	 */
	function buildUrl(url, p) {
		if (p) {
			var param = "";
			for (var key in p) {
				param += key + "=" + p[key] + "&";
			}
			param = param.lastIndexOf("&") == (param.length - 1)
					? param.substring(0, param.length - 1) : param;
			url += "?" + param;
		}
		return url;
	}
})(jQuery);

/**
 * 扩展表单验证
 */
$.extend($.fn.validatebox.defaults.rules, {
    after: {
        validator: function(value, param){
        	var t = $(param[0]).val();
        	if (t != "") {
        		var b = new Date(t.replace(/-/g, "/"));
        		var c = new Date(value.replace(/-/g, "/"));
        		return c.getTime() >= b.getTime();
        	} else {
        		return true;
        	}
        },
        message: "当前选择时间必须大于前置时间。"
    },
    before: {
    	validator: function(value, param){
        	var t = $(param[0]).val();
        	if (t != "") {
        		var b = new Date(t.replace(/-/g, "/"));
        		var c = new Date(value.replace(/-/g, "/"));
        		return c.getTime() <= b.getTime();
        	} else {
        		return true;
        	}
        },
        message: "当前选择时间必须小于后置时间。"
    },
    beforeCurrentDate: {
    	validator:function(value) {
    		var currentd = new Date();
    		var choosed = new Date(value.replace(/-/g, "/"));
    		
    		return (currentd.getTime()-1000*60*60*24) <= choosed.getTime();
    	},
    	message:'当前选择日期必须大于等于当前日期'
    },
    /**
     * 两个日期之间的校验，3个参数：开始日期的input、结束日期的input、提示文字
     */
    between: {
    	validator: function(value, param){
        	var start = $(param[0]).val();
        	var end = $(param[1]).val();
        	if (start != "" && end != "") {
        		var s = new Date(start.replace(/-/g, "/"));
        		var e = new Date(end.replace(/-/g, "/"));
        		var v = new Date(value.replace(/-/g, "/"));
        		return (v.getTime() >= s.getTime()) && (v.getTime() <= e.getTime());
        	} else {
        		return true;
        	}
        },
        message: "当前选择时间必须在{2}之间。"
    },
    amoutAfter: {
        validator: function(value, param){
        	var t = $(param[0]).val();
        	var isAmout = /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/i.test(value);
        	if(isAmout){
        		if (t != "") {
            		var b = t;
            		var c = value;
            		return c*1 >= b*1;
            	} else {
            		return true;
            	}
        	}else{
        		return false;
        	}
        	
        },
        message: "当前必须为金额且大于前置金额。"
    },
    amoutBefore: {
    	validator: function(value, param){
        	var t = $(param[0]).val();
        	var isAmout = /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/i.test(value);
        	if(isAmout){
        		if (t != "") {
            		var b = t;
            		var c = value;
            		return c*1 <= b*1;
            	} else {
            		return true;
            	}
        	}else{
        		return false;
        	}
        	
        },
        message: "当前必须为金额且小于后置金额。"
    },
	minLength:{// 判断最小长度
    	validator:function(value,param) {
    		return value.length>=param[0];
    	},
    	message:'最少输入 {0} 个字符。'
    },
	maxLength:{// 判断最大长度
    	validator:function(value,param) {
    		return value.length<=param[0];
    	},
    	message:'最多输入 {0} 个字符。'
    },
    phone:{// 验证固话或手机电话号码
    	validator:function(value) {
    		return /^((\(\d{2,4}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value) || /^(13|14|15|17|18)\d{9}$/i.test(value);
    	},
     	message:'固话格式:020-88888888或手机格式'
    },
    mobile:{// 验证手机号码或固话
    	validator:function(value) {
    		return /^(13|14|15|17|18)\d{9}$/i.test(value) || /^((\(\d{2,4}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
    	},
    	message:'手机号码或固话格式:020-88888888'
    },
    mobiles:{// 验证手机号码
    	validator:function(value) {
    		return /^(13|14|15|17|18)\d{9}$/i.test(value);
    	},
    	message:'手机号码格式不正确'
    },
    chuanzhen:{// 传真
    	validator:function(value) {
    		return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
    	},
    	message:'传真号码不正确'
    },
    idcard:{// 验证身份证
         validator:function(value) {
        	 return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value);
         },
         	 message:'身份证号码格式不正确'
     },
     orgCode:{//验证组织机构代码
    	 validator:function(value) {
        	 return /^([A-Za-z0-9]{9})?$/i.test(value);
         },
         	 message:'组织机构代码只能输入9位字母或数字'
     },
     taxCode:{//税号
    	 validator:function(value) {
        	 return /^([A-Za-z0-9]{15})?$/i.test(value);
         },
         	 message:'税号代码只能输入15位字母或数字'
     },
     lincenseCode:{//营业执照号码
    	 validator:function(value) {
        	 return /^([0-9]{15})?$/i.test(value);
         },
         	 message:'营业执照号码只能输入15位数字'
     },
     intOrFloat:{// 验证整数或小数
          validator:function(value) {
        	  return /^\d+(\.\d+)?$/i.test(value);
          },
          message:'请输入数字，并确保格式正确'
     },
     currency:{// 验证货币
          validator:function(value) {
        	  return /^\d+(\.\d+)?$/i.test(value);
          },
         message:'货币格式不正确'
     },
     chinese:{// 验证中文
         validator:function(value) {
        	 return /^[\u0391-\uFFE5]+$/i.test(value);
         },
    	message:'请输入中文'
	},
	nonumerical:{// 验证非数值
        validator:function(value) {
       	 return /^[^0-9]+$/i.test(value);
        },
        message:'请输入非数值类型'
	},
	bankNo:{// 验证银行卡数值类型
        validator:function(value) {
       	 return /^[0-9]{16,19}$/i.test(value);
        },
        message:'请输入长度为16-19位的银行卡号'
	},
	english:{// 验证英语
		validator:function(value) {
			return /^[A-Za-z]+$/i.test(value);
		},
		message:'请输入英文'
    },
    unnormal:{// 验证是否包含空格和非法字符
    	validator:function(value) {
    		return /.+/i.test(value);
    	},
    	message:'输入值不能为空和包含其他非法字符'
     },
     username:{// 验证用户名
    	 	validator:function(value) {
    		return /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i.test(value);
    	},
    		message:'用户名不合法（字母开头，允许6-16字节，允许字母数字下划线）'
	},
	zip:{// 验证邮政编码
	    	validator:function(value) {
	    	return /^[1-9]\d{5}$/i.test(value);
    	},
    	message:'邮政编码格式不正确'
    },
    ip:{// 验证IP地址
	    validator:function(value) {
	    	return /d+.d+.d+.d+/i.test(value);
	     },
	     message:'IP地址格式不正确'
    },
    email:{
    	 validator:function(value){
    		 return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value); 
    },
    	message:'请输入有效的电子邮件账号(例：abc@126.com)'
   },
   checkUnique:{
  	 validator:function(value,param){
  		var url = param[0];
  		var data = {};
  		for(var i=1;i < param.length;i++){
  			data[param[i]] = $("#"+param[i]).val();
  		}
  		var result = $.ajax({
  			async: false,
  			type : 'post',
  			url : url,
  			data : data
  		}).responseText;
  		if (result === "false") {
  			return false;
  		} else {
  			return true;
  		}
     },
  	 message:'输入有重复记录'
   },
   exist:{
	   validator:function(value,param){
  		 return value==param[0]?false:true; 
	   },
	   message:'系统已存在'
   },
   //身份证唯一性提示
   personIdCard:{
	   validator:function(value,param){
  		 return value==param[0]?false:true; 
	   },
	   message:'系统已存在'
   },
   //之前拼写错误的金额格式
   amoutNotZero:{
	   validator:function(value){
		   return /^(([1-9]\d*)(\.\d{1,2})?)$|(0\.0?([1-9]\d?))$/i.test(value);
	   },
	   message:'请输入不为0的金额格式'
   },
   //之前拼写错误的
   amout:{
	   validator:function(value){
		   return /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/i.test(value);
	   },
	   message:'请输入正确的金额格式'
   },
   //金额格式
   amountNotZero:{
	   validator:function(value){
		   return /^(([1-9]\d*)(\.\d{1,2})?)$|(0\.0?([1-9]\d?))$/i.test(value);
	   },
	   message:'请输入不为0金额格式'
   },
   //金额不能为0但可以负数
   amountNotZeroAll:{
	   validator:function(value){
		   return /^(-)?(([1-9]\d*)(\.\d{1,2})?)$|(0\.0?([1-9]\d?))$/i.test(value);
	   },
	   message:'请输入不为0金额格式'
   },
   //金额校验，支持长度参数，amount[16]则包括小数点后不能超过16位
   amount:{
	   validator:function(value, param){
		   var result = /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/i.test(value);
		   if(result){
			   if(param){
				   if(value.replace('.','').length > param[0]){
					   result = false;
				   }
			   }else{
				   if(value.replace('.','').length > 22){
					   result = false;
				   }
			   }
		   }
		   return result;
	   },
	   message:'请输入正确的保留2位小数的金额格式'
   },
   amountPlus:{
	   validator:function(value){
		   return /^(([1-9]{1}\d*)|([0]{0}))(\.(\d){1,2})?$/i.test(value)||/^([0]{1})\.(\d){1,2}?$/i.test(value);
	   },
	   message:'请输入大于0的保留2位小数的金额格式'
   },
   amountpointfour:{
	   validator:function(value){
		   return /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,4})?$/i.test(value);
	   },
	   message:'请输入正确的保留4位小数的金额格式'
   },
   naturalNumber:{//自然数0,1,2...
          validator:function(value) {
              return /^\d+$/i.test(value);
          },
          message:'请输入整数'
   },
   numberSection:{//数值区间校验
       validator:function(value, param) {
            return /^\d+(\.\d+)?$/i.test(value) && value >= eval(param[0]) && value <= eval(param[1]);
       },
       message:'请输入{0}~{1}之间数值'
   },
   percentageFormat:{//百分比形式（0-100之间的整数或浮点数）
	   validator:function(value, param) {
		   return /^((\d|[123456789]\d)(\.\d+)?|100)$/i.test(value);
	   },
	   message:'请输入正确的百分比格式,0-100之间的整数或浮点数'
   },
   url:{
	   validator:function(value) {
		   return /((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/i.test(value);
	   },
	   message:'请输入正确网址'
   },
   appointValue:{//指定值，如只能输入[1,2,3,4]
	   validator:function(value,param) {
		   for(var i=0;i<param.length;i++){
			   if(value==param[i])
				   return true;
		   }
		   return false;
	   },
	   message:'请输入正确的值'
   },
   progressSection:{//进度值区间校验
       validator:function(value, param) {
    	    var before = $(param[0]).val();
    	    var after = $(param[1]).val();
    	    var preProgress=$(param[2]).val();
            return /-?(0|[1-9]\d*)(\.\d+)?$/i.test(value) && value >= eval(before-preProgress) && value <= eval(after-preProgress);
       },
       message:'输入进度+历史累计进度应在里程碑范围内'
   },
   qq:{
	   validator:function(value){
		   return /^[1-9]\d{4,10}$/i.test(value);
	   },
	   message:'请输入正确的QQ格式'
   }
   ,
   maxFee: {
       validator: function(value, param){
       	var t = $(param[0]).val();
       	if (t != "") {
       		return parseFloat(value) >= parseFloat(t);
       	} else {
       		return true;
       	}
       },
       message: "当前填写金额必须大于前置金额。"
   },
   minFee: {
   	validator: function(value, param){
       	var t = $(param[0]).val();
       	if (t != "") {
       		return parseFloat(value) <= parseFloat(t);
       	} else {
       		return true;
       	}
       },
       message: "当前填写金额必须小于后置金额。"
   },
   floatTwo:{
	   validator: function(value, param){
		   return /^\d+([\.]\d{2})?$/i.test(value);
	   },
	   message:"请输入整数或2位小数"
   }
   
});